状态 Vuex 不能正常工作 Nuxt.js 问题
State Vuex don't work correctly with Nuxt.js Problem
我正在尝试在我的 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
钩子中发出的,但是 Nuxt 不会等待它解析,因为没有 returned,所以它会一直渲染组件,因此 运行 created
和 mounted
挂钩,在调用时尚未填充 $store
.
为了让它工作,你应该 return 来自 fetch
方法的承诺。
如果您的应用中没有其他代码,只需添加 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);
})
}
我正在尝试在我的 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
钩子中发出的,但是 Nuxt 不会等待它解析,因为没有 returned,所以它会一直渲染组件,因此 运行 created
和 mounted
挂钩,在调用时尚未填充 $store
.
为了让它工作,你应该 return 来自 fetch
方法的承诺。
如果您的应用中没有其他代码,只需添加 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);
})
}