【问题标题】:Nuxt Vuex mutation runs but doesn't update stateNuxt Vuex 突变运行但不更新状态
【发布时间】:2020-03-16 07:49:45
【问题描述】:

我正在尝试通过 nuxtServerInit 获取一些数据并将其保存在 state 中

存储/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 开发工具也没有显示帖子 [] 中的数据。
我在这里错过了什么?

【问题讨论】:

    标签: vue.js vuex nuxt.js


    【解决方案1】:

    看起来nuxtServerInit 是作为带有 Nuxt context 的操作分派的。作为一个动作,第一个参数将是 Vuex context

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

    docs 也说:

    注意:异步 nuxtServerInit 操作必须返回 Promise 或利用 async/await 以允许 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)
    }
    

    【讨论】:

    • 感谢它解决了“未定义的'长度'”错误,但开发工具仍然显示没有更新
    • 你能张贴截图说明你的意思吗?因为这个函数在服务器端运行,所以它可能看起来与更新 Vuex 状态客户端时不同。
    • 看起来像这样 imgur.com/a/ITHUxax 。代码显示状态已更新,但开发工具未显示任何更新
    • 刚刚在文档中看到了这句话:“注意:异步 nuxtServerInit 操作必须返回一个 Promise 或利用 async/await 来允许 nuxt 服务器等待它们。”将更新我的答案以使用异步/等待。听起来服务器在获取数据之前正在响应。
    猜你喜欢
    • 2019-08-17
    • 2020-12-18
    • 2019-11-30
    • 2020-09-10
    • 2018-05-13
    • 2022-01-09
    • 2020-04-08
    • 2019-08-06
    • 2021-06-19
    相关资源
    最近更新 更多