如何让nuxtServerInit在服务器上调度操作?

时间:2019-05-12 21:14:43

标签: vuejs2 nuxt.js

我有一个使用firebase的nuxt项目。我想使用SSR并在SSR上初始化并填充商店,但是我无法使下面的代码正常工作。

我正在开发nuxt项目,我有一个启动firebase sdk的插件/ firebase项目。我有一个有效的asyncData函数。

在我的/store/index.js文件中,导出状态函数和操作。在动作中,我有一个异步nuxtServerInit,它通过上下文分派一个`posts / getPosts'动作。

我的store/index中有

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

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

在我的“ store / 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并且存在状态值(空数组)。这告诉我,至少在客户端,商店已启动并且模块存在。

1 个答案:

答案 0 :(得分:0)

事实证明问题不在于我的动作,而在于突变。这是使我工作的最终代码。

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