简体   繁体   English

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

[英]Nuxt Vuex mutation runs but doesn't update state

I'm trying to get some data by nuxtServerInit and save it in state我正在尝试通过 nuxtServerInit 获取一些数据并将其保存在状态

store/index.js商店/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)
    })
  }
}

when I run this code console output is当我运行此代码时,控制台输出是

mutation => 1                                                                                                                      
mutation => 2                                                                                                                      
mutation => 3                                                                                                                      

ERROR  Cannot read property 'length' of undefined    

And vue dev tools also doesn't show there's data inside posts[]. vue 开发工具也没有显示posts[] 中有数据。
What am I missing here?我在这里缺少什么?

It looks like nuxtServerInit is dispatched as an action with the Nuxt context .看起来nuxtServerInit是作为具有 Nuxt上下文的操作进行调度的。 Being an action, the first argument will be the Vuex context .作为一个动作,第一个参数将是 Vuex上下文

The Vuex context exposes several properties including state and commit . Vuex 上下文公开了几个属性,包括statecommit

The docs also say: 文档还说:

Note: Asynchronous nuxtServerInit actions must return a Promise or leverage async/await to allow the nuxt server to wait on them.注意:异步nuxtServerInit操作必须返回一个 Promise 或利用 async/await 来允许nuxt服务器等待它们。

You can change your code to:您可以将代码更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM