首页 > 解决方案 > Vue.js, vuex with Firebase cloud firestore, 在数据库中添加或删除任何记录后更新前端

问题描述

两个问题

  1. 我想在向我的 firestore 数据库提交任何操作后更新前端,假设我有一组通过 store.js 文件中的 getter 呈现给前端的项目。在我的 .vue 组件中,我有一个添加、删除或更新来自数据库的项目的功能,该功能工作正常,但我必须刷新页面才能在我的应用程序中反映更新,下面的代码是.vue 组件中的一个简单示例

export default {
  //....
  
  computed:{
    items: {
      return this.$store.getters.Items 
    }
  },
  methods :{
    removeItem(id) {
      this.$store.dispatch('removeItem', id)
    }
  }
}
<template> 
<div >
  <ul v-for="item in items" :key="item.id">
    <li> {{item.name}} <button @click="removeItem(item.id)">X</button></li> 
  </ul>
    
  </div>
</template>

这是我的 store.js 文件的示例

import db from 'firebase/init.js'

state: {
  items: []
},

mutations: {
  SETMENUITEMS(state, items) {
    state.items = items
  }
  REMOVEITEM(state, id) {
    state.menuItems.filter(item => {
      return item.id != id
    })
  }
},

actions: {
  //I dispatch this action  in the created life hook of my root .vue app component to have the items loaded upon initilizing the app
  fetchMenuItems({commit}){
    const menuItems = []
      db.collection('myCollection').get()
        .then(snapshot => {
          snapshot.forEach(doc => {
            let item = doc.data()
            item.id = doc.id;
            menuItems.push(item)
          })
          commit('SETMENUITEMS', menuItems)
        })
        .catch(err => console.log(err))
  },
  removeItem({commit}, id){
    db.collection('myCollection').doc(id).delete()
      .then(() => {
        //at this point the item is already deleted from the database but since the ap didn't reload the item is still showing 
        commit('REMOVEITEM', id)
      })
      .catch(err => console.log(err.message)
  }
},

getters: {
  Items: state => state.items
}

  1. 现在,有人可以告诉我如何简单地从 Firestore 中删除整个集合,并将结果反映在我的前端。

请在下面留下评论,以进一步说明所需的行为,对于这个冗长的问题感到抱歉,并在此先感谢。

标签: firebasevue.jsgoogle-cloud-firestorevuex

解决方案


我将尝试回答第一个问题。

当承诺得到解决时,您将致力于商店。我认为承诺只解决一次。

尝试使用 onSnapshot 将您的代码直接附加到集合中,这样您就可以将观察者直接传递给集合 observable:

...

actions: {
  //I dispatch this action  in the created life hook of my root .vue app component to have the items loaded upon initilizing the app
  fetchMenuItems({commit}){
    const menuItems = []
      db.collection('myCollection').onSnapshot(snapshot => {
          snapshot.forEach(doc => {
            let item = doc.data()
            item.id = doc.id;
            menuItems.push(item)
          })
          commit('SETMENUITEMS', menuItems)
        })
        .catch(err => console.log(err))
  },
  removeItem({commit}, id){
    db.collection('myCollection').doc(id).delete()
      .then(() => {
        //at this point the item is already deleted from the database but since the ap didn't reload the item is still showing 
        commit('REMOVEITEM', id)
      })
      .catch(err => console.log(err.message)
  }
},

...

如您在文档中看到的那样,不建议从 Web 客户端删除整个集合:删除数据


推荐阅读