首页 > 解决方案 > Vuex 突变通过异步/等待操作更新具有动态属性名称的对象

问题描述

所以我试图让 Nuxt 查询我的 GQL API 以获取站点菜单。我通过我的商店模块nuxtServerInit中的功能来做到这一点。index.js

像这样:

menuLocations = ["MAIN_MENU", "WORK_MENU"]
store.dispatch("menus/QUERY_MENUS", menuLocations)

QUERY_MENUS从我的menus.js商店模块调用我的操作。代码是这样的:

// Define State defaults
export const state = () => ({
    locations: {}
})

// Define mutations
export const mutations = {
    SET_MENU(state, data) {
        //Vue.set(state.locations, data.location, data.items)
        //state.locations = { ...state.locations, [data.location]: data.items }
    }
}

// Define actions
export const actions = {
    async QUERY_MENUS({ commit }, menuLocations) {
        let client = this.app.apolloProvider.defaultClient

        // Get each menu from server
        for (const location of menuLocations) {
            const query = await client.query({
                query: MenuByLocation,
                variables: {
                    location: location
                }
            })

            // Commit menu to store
            commit("SET_MENU", {
                location: _camelCase(location),
                items: _get(query, "data.menuItems.nodes", {})
            })
        }
    }
}

问题是注释掉的行都SET_MENU不能可靠地工作(当未注释时),有时它们工作,有时它们不工作。我猜它与 Nuxt 和 SSR 有关,或者我做错了异步/等待的东西?

代码沙盒在这里:

代码:https ://codesandbox.io/s/j3yjz2wm6y?fontsize=14

预览:https ://j3yjz2wm6y.sse.codesandbox.io/

有什么建议么?谢谢!

标签: vue.jsvuexnuxt.jsvue-apollo

解决方案


在提供的沙箱中有两个错误:

1) nuxtServerInit 中没有等待调度

export const actions = {
  async nuxtServerInit(store, context) {
    let menuLocations = ["MAIN_MENU", "OUR_WORK_MENU"];
    await store.dispatch("menus/QUERY_MENUS", menuLocations);
  }
};

2) 在计算属性中缺少状态引用

  return _get(this, "$store.state.menus.locations.mainMenu", false);

这里修复了 CBS -> https://codesandbox.io/s/rrrv17oq8m


推荐阅读