在 vuex 操作中访问 this.$fireStore (Nuxt.js)

vsh*_*hna 2 firebase vue.js vuefire nuxt.js google-cloud-firestore

这里声明$fireStore可以在vuex action中访问:

async randomVuexAction({ commit, state, rootState }, userId) {
  const ref = this.$fireStore.collection('users').doc(userId)
  ...
}
Run Code Online (Sandbox Code Playgroud)

问题:在 中触发操作后store/index.js

addItem: ({ commit, getters }, itemName) => {
  const item = { name: itemName }
  this.$fireStore.collection('items').add(item).then((res) => {})
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:Cannot read property '$fireStore' of undefined。一般来说,console.log(this)除了nuxtServerInit()- 之外的所有操作中都会给出undefined。那么是否有可能使用$fireStore或者vuex文档具有误导性?

小智 5

尝试删除您的操作的箭头符号(因为“this”与箭头符号指的不是同一件事),即

addItem ({ commit, getters }, itemName) {
  const item = { name: itemName }
  this.$fireStore.collection('items').add(item).then((res) => {})
}
Run Code Online (Sandbox Code Playgroud)

注意:这同样适用于 Vue 组件中的计算属性和方法。遵循文档,不要为了改变而改变。