【问题标题】:Vue-Firebase: Updating children & writing to childVue-Firebase:更新孩子并写信给孩子
【发布时间】:2018-11-24 14:33:37
【问题描述】:

我开始使用 Firebase 和 Vue,也使用 VueFire,但我不明白如何在 Firebase 更新子节点。

我打开了一个 firebase 项目并连接到它,我可以向它推送数据。

Firebase

我做了一个vue组件

 import db from '../FireBase'

  let team = db.ref('Teams');//Reference to Teams at firebase 
  let miss = db.ref().child('Teams'); //Attempt to get to the children of Teams 
  export default {
    name: "App",
    firebase: {
      Teams_loc: db.ref('Teams'),
      Mission: this.Teams_loc.child('Teams'),
    missionKey:  db.ref().child('Teams').push("").key,
    },
...

我设法从 firebase 获取 Teams 并向其发送数据:

this.$firebaseRefs.Teams_loc.push({
    "test": "tester"
});

这很有效,但是当我尝试更新里面的孩子时

this.miss.push({
              "where": "am i"
            })

我收到以下错误

Cannot read property 'child' of undefined

当我尝试更新孩子时

this.$firebaseRefs.missionKey.update(arr[0]);//arr[0] is an object

我尝试查看了很多地方,但似乎没有任何效果。

谢谢,

【问题讨论】:

    标签: firebase firebase-realtime-database vue.js vue-component


    【解决方案1】:

    当您执行以下操作时,您在第二行出现错误。

      Teams_loc: db.ref('Teams'),
      Mission: this.Teams_loc.child('Teams'),
    

    Teams 节点的子节点没有具有值为 `Teams 的键。

    因此,如果要更新项目,首先必须获取其密钥(例如-LEzOBT-mp.....)并按照文档中的说明执行以下操作:

    updateItem: function (item) { 
       // create a copy of the item
       const copy = {...item}
       // remove the .key attribute
       delete copy['.key']
       //possibly update (or add) some values of (to) the item
       this.$firebaseRefs.Teams_loc.child(item['.key']).set(copy)
    }
    

    另外(如果我没记错的话)db.ref() 会产生错误,因为您必须将值传递给 ref()

    我建议你多研究一下文档和示例:https://github.com/vuejs/vuefirehttps://github.com/vuejs/vuefire/blob/master/examples/todo-app/index.html


    根据您的评论进行更新。关于如何“知道随机生成的密钥”的详细信息

    根据文档:

    绑定数组中的每条记录都将包含一个 .key 属性,该属性 指定存储记录的键。所以如果你有数据 /Teams/-LEzOBT-mp...../,该数据的记录将有一个 .key “-LEzOBT-mp.....”。

    查看文档的这一部分:https://github.com/vuejs/vuefire#array-bindings

    因此,您将获得 Teams 对象的所有键。您现在必须选择要更新的项目。

    您还可以在您的 firebase 对象中声明一个查询,例如:

      firebase: { 
        team21483: this.database
                .ref('Teams')
                .orderByChild('teamCode')
                .equalTo('21483') 
      }
    

    你会得到一个只有一个团队的数组,即TeamCode = 21483

    在这种最新情况下,最好的方法是使用您传递给 equalTo() 的变量,使用 $bindAsArray(或者可能是 $bindAsObject)实例方法手动绑定到此 Firebase 查询。

    【讨论】:

    • 我知道我是否可以获得密钥,这会使事情变得更容易,但问题是我想生成条目并删除它们,所以我不确定我如何知道我在 firebase 中获得的随机生成的密钥.
    • 好的,我明白了。我想我还有很多东西要学。我会按照你给我的指导开始工作。非常感谢!
    猜你喜欢
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多