Nuxt Vuex突变运行但不更新状态

时间:2020-03-16 07:49:45

标签: 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('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开发人员工具也不会显示帖子内部有数据[]。
我在这里想念什么?

1 个答案:

答案 0 :(得分:0)

似乎nuxtServerInit是作为Nuxt context的动作而分派的。作为一个动作,第一个参数将是Vuex context

Vuex上下文公开了多个属性,包括statecommit

docs也说:

注意:异步nuxtServerInit操作必须返回Promise或利用异步/等待来允许nuxt服务器等待它们。

您可以将代码更改为:

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)
}