首页 > 解决方案 > 如何让 nuxtServerInit 在服务器上调度操作?

问题描述

我有一个使用 firebase 的 nuxt 项目。我想使用 SSR 并在 SSR 上启动和填充商店,但我无法让下面的代码工作。

我正在开发一个 nuxt 项目我有一个插件/firebase 项目,它启动了 firebase sdk。我有一个可以工作的 asyncData 函数。

在我的 /store/index.js 文件中,我导出状态函数和操作。在操作中,我有一个异步 nuxtServerInit,它分派一个传递上下文的“posts/getPosts”操作。

在我的store/index我有

export const state = () => ({})

export const actions = {
  async nuxtServerInit({ dispatch }, context) {
    await dispatch('posts/getPosts', context)
  }
}

在我的“商店/posts.js”中,我有

import { db } from '~/plugins/firebase'

export const state = () => ({
  ActivePosts: []
})

export const actions = {
  getPosts({ commit }) {
    const postList = []
    return db
      .collection('posts')
      .where('status', '==', 'approved')
      .orderBy('CreatedAt', 'desc')
      .get()
      .then(docs => {
        docs.forEach(doc => {
          const newPost = doc.data()
          newPost.id = doc.id
          this.postList.push(newPost)
          console.log(newPost)
        })
      })
      .then(() => {
        commit('addPosts', postList)
      })
      .catch(e => console.log(e))
  }
}

在我的firebase插件中,我有

import firebase from 'firebase'

const firebaseConfig = {
  apiKey: '<<correctkey>>.',
  authDomain: '<<correctkey>>',
  databaseURL: '<<correctUrl>>',
  projectId: '<<correctid>>',
  storageBucket: '<<correctbucket>>',
  messagingSenderId: '<<correctkey>>',
  appId: '<<correctkey>>'
}

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig)
}

export const db = firebase.firestore()
export const auth = firebase.auth()

至少我认为这段代码应该在服务器上启动我的存储并用帖子值填充它。当我在 vue 开发人员工具中检查我的商店时,商店中没有值,尽管 getter 存在并且状态值(空数组)存在。这告诉我存储已启动并且模块存在,至少在客户端。

标签: vuejs2nuxt.js

解决方案


原来问题不在于我的行为,而在于突变。这是让我开始工作的最终代码。

import { db } from '~/plugins/firebase'

export const state = () => ({
  ActivePosts: []
})

export const getters = {
  getPosts(state) {
    return state.ActivePosts
  }
}

export const mutations = {
  addPosts(state, payload) { // had to change { state } to state.
    state.ActivePosts.push(payload)
  }
}

export const actions = {
  getPosts({ commit }) {
    const postList = []
    return db
      .collection('posts')
      .where('status', '==', 'approved')
      .orderBy('CreatedAt', 'desc')
      .get()
      .then(docs => {
        docs.forEach(doc => {
          const newPost = doc.data()
          newPost.id = doc.id
          postList.push(newPost) //removed the `this.`
        })
          commit('addPosts', postList) //moved the commit to the  // moved the commit out of its own then.
      })
      .catch(e => console.log(e))
  }
}

推荐阅读