我正在尝试在我的 Nuxt.js 应用程序上设置状态 vuex,但它无法正常工作。 所以在这里我用 fetch 方法设置我的状态:
fetch({app, store, route}) {
app.$axios.$get(`apps/${route.params.id}`)
.then(res => {
store.dispatch('setApp', {
...res,
id: route.params.id
})
console.log(app.store.state.app);
})
}
当我登录 app.store 时,这里一切正常,数据在那里, 但是当我尝试登录时:
created() {
console.log(this.$store);
},
mounted() {
console.log(this.$store);
}
这是我的商店代码:
const store = () => new Vuex.Store({
state: {
app: ''
},
mutations: {
'SET_APP' (state, payload) {
state.app = payload
}
},
actions: {
setApp (ctx, payload) {
ctx.commit('SET_APP', payload)
}
},
getters: {
}
})
我不工作我的状态是空的所以数据没有呈现在我的模板上( 我希望有人能帮助我!
P.S:同样,当它在客户端登录时一切正常,但在 SSR 中却不行(
最佳答案
如 docs 所述
To make the fetch method asynchronous, return a Promise, Nuxt.js will wait for the promise to be resolved before rendering the component.
在上面的代码示例中,axios 请求是在 fetch
钩子(Hook)中发出的,但是 Nuxt 不会等待它解析,因为没有返回任何 promise,因此它会继续渲染组件,从而运行 created
和 mounted
Hook ,在调用时尚未填充 $store
。
为了让它工作,你应该从 fetch
方法返回一个 promise 。
如果您的应用中没有其他代码,只需添加 return
语句即可解决问题:
fetch({app, store, route}) {
return app.$axios.$get(`apps/${route.params.id}`)
.then(res => {
store.dispatch('setApp', {
...res,
id: route.params.id
})
console.log(app.store.state.app);
})
}
关于javascript - 状态 Vuex 不能与 Nuxt.js 问题一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53045871/