我创建了一个 Nuxt 模块,它的 store 模块中有一个 nuxtServerInit 方法。我将它链接到 store 文件夹下的 index.js,因为在 vuex 模块模式下,只有 index.js 文件可以调用 nuxtServerInit。然而,主应用程序的存储(我正在添加我的自定义模块)是空的。我不确定如何进行。我希望在呈现页面之前触发我的自定义模块中的 nuxtServerInit ,但是没有任何反应。
~/modules/my_module/store/modules/user.js
export default options => ({
namespaced: true,
state: () => ({
...
})
,
actions : {
async nuxtServerInit({}, { app, store }) {
...
},
}
})
~/modules/my_module/store/index.js
import userModule from './modules/user'
// get the options out using lodash templates
const options = JSON.parse(`<%= JSON.stringify(options) %>`)
// extract the namespace var
const { namespace } = options
// create the plugin
export default ({ store }, inject) => {
// register the module using namespace as the name.
// counter module takes the options object and returns an object that is a
// vuex store defenition
store.registerModule(namespace, userModule(options), {
preserveState: Boolean(store.state[namespace]) // if the store module already exists, preserve it
})
}
export const actions = {
async nuxtServerInit({ dispatch }) {
await dispatch(userModule.actions.nuxtServerInit)
},
}
~/store/index.js
import userModule from '~/modules/my_module/store/modules/user'
export default actions = {
async nuxtServerInit({ dispatch }) {
await dispatch(userModule.actions.nuxtServerInit)
}
}