firebase - Vue.js, vuex with Firebase cloud firestore, 在数据库中添加或删除任何记录后更新前端
问题描述
两个问题
- 我想在向我的 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
}
- 现在,有人可以告诉我如何简单地从 Firestore 中删除整个集合,并将结果反映在我的前端。
请在下面留下评论,以进一步说明所需的行为,对于这个冗长的问题感到抱歉,并在此先感谢。
解决方案
我将尝试回答第一个问题。
当承诺得到解决时,您将致力于商店。我认为承诺只解决一次。
尝试使用 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 客户端删除整个集合:删除数据
推荐阅读
- python - Azure Functions 中的凭据,传递一个凭据或根据需要调用?
- flutter - 如何对齐文本?
- sql - 更新语句,更新值是有条件评估的
- javascript - 无法更新 redux 存储 - React Native
- python - Python SAML 身份验证自动化
- swiftui - SwiftUI Hero Animation (matchedGeometryEffect) 问题
- python - 如何在 Python 上运行 PyPi 包命令
- javascript - 为什么当我关闭选项卡时 onload() 不起作用?
- reverse-engineering - 整个二进制文件的控制流程图
- javascript - 循环数组的谷歌脚本在第一次运行后变得未定义