【发布时间】:2021-04-24 20:17:08
【问题描述】:
我正在开发一个网络应用程序,用户可以在其中添加和删除通知。
为了在firestore中找到要删除的正确通知,我在通知文档中添加了一个id字段,并在DOM中通知的data-id属性中添加了相同的id。然后我使用 .where 方法找到该文档并将其删除。
当我调用 getNotifications() 函数来更新 DOM 时,问题就来了。删除文档似乎需要几毫秒,因此在文档消失之前调用了getNotifications()。因此,它有时会返回包含已删除通知的集合,并且通知仍会呈现给 DOM。
我尝试在调用函数之前将超时设置为 100 毫秒,然后一切正常。但是,这似乎不是最好的解决方案。
有人对此有很好的解决方案吗?任何帮助深表感谢! :)
export default {
data() {
return {
messages: []
}
},
methods: {
getNotifications() {
const self = this;
const db = firebase.firestore()
this.messages = [];
db.collection("messages").get()
.then(function(snapshot){
snapshot.forEach(function(doc){
self.messages.push(doc.data());
})
})
},
deleteNotification(e) {
const self = this;
const id = e.target.parentElement.parentElement.getAttribute("data-id");
const db = firebase.firestore()
db.collection("messages").where("id", "==", id).get()
.then(function(res) {
res.forEach(function(doc) {
doc.ref.delete();
console.log("Document deleted")
})
})
.then(function() {
self.getNotifications();
})
.catch(function(error) {
console.log("Error deleting document: ", error)
})
}
},
created() {
this.getNotifications()
}
}
【问题讨论】:
标签: javascript firebase vue.js google-cloud-firestore