Vuex突变使用来自异步/等待操作的动态属性名称更新对象

时间:2019-05-02 09:59:35

标签: vue.js vuex nuxt.js vue-apollo

所以我想让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/

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:0)

在提供的沙箱中,出现两个错误:

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