vue.js - 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/
有什么建议么?谢谢!
解决方案
在提供的沙箱中有两个错误:
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
推荐阅读
- python - 避免python中的for循环正常(size = {}))
- scala - 在 scala 宏中,如何获取类在运行时的全名?
- ios - iOS 13 - 未加载库:AppTrackingTransparency.framework/AppTrackingTransparency
- node.js - Puppeteer:会话关闭。该页面很可能已关闭
- javascript - 是否可以通过控制台检测注入的 Javascript?
- reactjs - React App 仅在第一次状态更改时重新渲染,即使更改成功,第二次更改也不可见
- javascript - 将数据从asp.net mvc中的2个不同jquery传递到同一个控制器
- python-3.x - Python3.8:将一个数据文件拆分为多个文件,所有文件均由文件中的关键字命名
- r - 上传多张人脸图像(5-10 张人脸图像,相同尺寸),更改为矩阵并在 R Shiny 中从头开始执行 PCA
- python - 在 Eclipse FileNotFoundError 上设置 Selenium 和 Python:[WinError 2]