【问题标题】:Vue & Firebase: Dom not updating when deleting documentVue 和 Firebase:删除文档时 Dom 不更新
【发布时间】: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


    【解决方案1】:

    这也是我在第一个 firebase 项目中遇到的问题。解决此问题的最简单方法是使用实​​时更新。您可以配置getNotifications() 方法,使其最初加载通知并订阅更新。这意味着您不必手动刷新删除通知 - 订阅会为您执行此操作。订阅通常会在几毫秒内对删除做出反应。

    您可以查看this 页面上的文档。

    【讨论】:

    • 像魅力一样工作 :) 谢谢!
    【解决方案2】:

    几点建议:

    1. 如果您已经拥有该 ID,则无需去获取该文档即可将其删除。您可以简单地执行以下操作:
    const ref = db.collection("messages").doc(id)
    await ref.delete()
    
    1. 您的代码不起作用的原因是,您在删除文档时正在执行异步操作,但您在返回并继续执行下一个 .then 块之前并未等待该操作解决。使用您的 se-up,您最终会得到不理想的嵌套 .then/.catch 块。
    2. 查看 Async/Await :)

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2020-03-08
      • 2015-07-30
      • 2021-08-23
      • 1970-01-01
      相关资源
      最近更新 更多