所以我试图让 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/
有什么建议么?谢谢!