Vue.js Nuxt Vuex突变运行但不';更新状态
我正试图通过nuxtServerInit获取一些数据,并将其保存在状态 store/index.jsVue.js Nuxt Vuex突变运行但不';更新状态,vue.js,vuex,nuxt.js,Vue.js,Vuex,Nuxt.js,我正试图通过nuxtServerInit获取一些数据,并将其保存在状态 store/index.js import { fireDb } from '~/plugins/firebase' export const state = () => ({ posts: [] }) export const mutations = { addPosts (state, post) { state.posts.push(post) console.log('mutatio
import { fireDb } from '~/plugins/firebase'
export const state = () => ({
posts: []
})
export const mutations = {
addPosts (state, post) {
state.posts.push(post)
console.log('mutation =>', state.posts.length)
}
}
export const actions = {
nuxtServerInit (state, ctx) {
fireDb.collection('posts').orderBy('timestamp', 'desc').limit(3).get().then((snapshot) => {
snapshot.forEach((doc) => {
state.commit('addPosts', doc.data())
})
console.log('action => ', state.posts.length)
})
}
}
当我运行此代码时,控制台输出为
mutation => 1
mutation => 2
mutation => 3
ERROR Cannot read property 'length' of undefined
vue开发工具也没有显示帖子[]中的数据。我在这里遗漏了什么?看起来
nuxtServerInit
是作为一个带有Nuxt的操作进行调度的。作为一个动作,第一个参数是Vuex
Vuex上下文公开了几个属性,包括state
和commit
政府还说:
注意:异步numxtserverinit
操作必须返回一个承诺,或者利用异步/await来允许numxt
服务器等待它们
您可以将代码更改为:
async nuxtServerInit({state, commit}, ctx) {
let snapshot = await fireDb.collection('posts').orderBy('timestamp', 'desc').limit(3).get();
snapshot.forEach((doc) => {
commit('addPosts', doc.data())
});
console.log('action => ', state.posts.length)
}
看起来
nuxtServerInit
是作为带有Nuxt的操作进行调度的。作为一个动作,第一个参数是Vuex
Vuex上下文公开了几个属性,包括state
和commit
政府还说:
注意:异步numxtserverinit
操作必须返回一个承诺,或者利用异步/await来允许numxt
服务器等待它们
您可以将代码更改为:
async nuxtServerInit({state, commit}, ctx) {
let snapshot = await fireDb.collection('posts').orderBy('timestamp', 'desc').limit(3).get();
snapshot.forEach((doc) => {
commit('addPosts', doc.data())
});
console.log('action => ', state.posts.length)
}
感谢它解决了“'length'of undefined”错误,但是开发工具仍然显示没有任何更新。你能发布一个屏幕截图来说明你的意思吗?由于此函数在服务器端运行,因此它可能与更新Vuex state客户端时的外观不同。代码表示状态已更新,但开发工具未显示任何更新。我们在文档中看到这样一句话:“注意:异步nuxtServerInit操作必须返回承诺或利用async/await允许nuxt服务器等待。”将更新我的答案以使用async/await。听起来服务器在获取数据之前做出了响应。感谢它解决了“'length'of undefined”错误,但是开发工具仍然显示没有任何更新。你能发布一个屏幕截图来说明你的意思吗?由于此函数在服务器端运行,因此它可能与更新Vuex state客户端时的外观不同。代码表示状态已更新,但开发工具未显示任何更新。我们在文档中看到这样一句话:“注意:异步nuxtServerInit操作必须返回承诺或利用async/await允许nuxt服务器等待。”将更新我的答案以使用async/await。听起来服务器在获取数据之前正在响应。