【问题标题】:Vuejs & Firestore - How to Update when Data Changes in FirestoreVuejs 和 Firestore - 如何在 Firestore 中的数据更改时进行更新
【发布时间】:2018-08-22 07:03:21
【问题描述】:

我已经阅读了大量教程和文档,但当 Firestore 中的数据发生变化时,我似乎无法在页面上进行更新(注意:不是 Firebase)

这是我目前所拥有的一切正常,除非数据库中的数据发生变化,除非我刷新,否则它不会反映在页面本身上。下面的代码在脚本标签内:

 import { recipeRef } from '../../firebase';
 export default {
 data() {
  return {
    recipes: []
  }
},
firestore: {
  recipes: recipeRef
},
created() {
  db.collection('recipes').get().then((onSnapshot) => {
    this.loading = false
    onSnapshot.forEach((doc) => {
      let data = {
        'id': doc.id,
        'name': doc.data().name
      }
      this.recipes.push(data)
    })

  })
}

我没有使用 Vuex。添加数据,编辑和阅读工作正常。只是在数据发生变化后不反映变化。也许我应该使用一个生命周期钩子?对于“onSnapshot”——我试过“snap”、“querySnapshot”等。没有运气。

提前致谢。

【问题讨论】:

    标签: firebase vue.js google-cloud-firestore


    【解决方案1】:

    删除 get() 并替换为快照 - 就像这样

    created() {
      db.collection('recipes').onSnapshot(snap => {
          let foo = [];
          snap.forEach(doc => {
           foo.push({id: doc.id, name: doc.data().name})
    
           });
        }
    });
    

    【讨论】:

    • 不是说要打数据库,会很贵吗?
    【解决方案2】:

    我不熟悉 firestore API,但浏览文档,看起来调用 get() 是您一次查询的方式。您拥有onSnapshot 的位置实际上应该是querySnapshot - 即一个查询的结果。见:

    对比:

    因此,要获得实时更新,您似乎需要创建一个侦听器,如下所示:

    db.collection('recipes')
        .onSnapshot(function(snapshot) {
            snapshot.forEach(function(doc) {
                // Find existing recipe in this.recipes
                // and swap in the new data
            });
        }, function(error) {
            // handle errors
        });
    

    我认为您需要将该侦听器添加到您当前正在执行的get() 查询中。希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 1970-01-01
      • 2018-04-01
      • 2020-09-09
      • 2022-06-16
      • 2019-09-30
      • 1970-01-01
      • 2021-12-03
      • 2022-01-01
      相关资源
      最近更新 更多