Vue-Firebase:更新儿童和儿童写给孩子

时间:2018-06-14 18:34:18

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

我开始使用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获取团队并向其发送数据:

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

我试着看了很多地方,但似乎什么也没做。

谢谢,

1 个答案:

答案 0 :(得分:0)

执行以下操作时,您在第二行发生错误。

  Teams_loc: db.ref('Teams'),
  Mission: this.Teams_loc.child('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

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