【发布时间】:2019-09-29 21:29:19
【问题描述】:
我有一个使用 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)
}
}
在我的“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()
至少我认为这段代码应该在服务器上启动我的存储并用 post 值填充它。当我在 vue 开发人员工具中检查我的商店时,商店中没有值,尽管存在 getter 并且存在状态值(空数组)。这告诉我存储已启动并且模块存在,至少在客户端。
【问题讨论】:
-
你的
console.log(newPost)显示什么了吗?当您推送到 postList 时,我认为您不需要“this”。commit('addPosts', postList)不需要它自己的 '.then',你可以把它放在你的 for 循环之后。 -
我在终端中没有任何日志。这就是为什么我认为它根本没有在服务器上运行
-
你确定 doc.data() 作为一个函数是对的吗? Console.log(doc) 看看你得到了什么。