vuejs2 - 如何让 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 存在并且状态值(空数组)存在。这告诉我存储已启动并且模块存在,至少在客户端。
解决方案
原来问题不在于我的行为,而在于突变。这是让我开始工作的最终代码。
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))
}
}
推荐阅读
- macros - 如何使用 gensym 符号捕获宏变量?
- android - 如何在 Kotlin Andorid 中读取 Apollo 客户端响应/GraphQL 响应的响应数据
- user-interface - 如何垂直打破水平滚动列表?
- aframe - 无法为一帧项目中的动画设置触发事件
- amazon-web-services - 如何根据文件名将一组文件上传到特定文件夹到 AWS S3
- julia - 如何停用?
- google-apps-script - Google Sheets Script - 如何在同一个电子表格中自动化“如果复选框 == true,然后在另一张表中复制行”?
- ios - 从 NSUserDefaults 检索自定义对象
- reactjs - 我的 redux thunk Axios 调用在我的 Redux 存储中返回空对象
- python - 使用 opencv(带掩码)从特定连接组件获取统计信息