使用Vue将新子项添加到实时Firebase数据库

时间:2018-05-01 08:04:49

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

模板:

<div class="addPlant" v-else-if="addPlantShow">
  <div>
    <h5 class="goBack"@click="handleBackToCollection()">Back to {{selectedCollection.collectionName}}</h5>
    <h2>Add Plant to {{selectedCollection.collectionName}}</h2>
  </div>
  <div>
    <form v-on:submit.prevent="addPlant(selectedCollection)">
    <div>
      <label for="plantName">Name: </label>
      <input type="text" id="plantName" v-model="newPlant.plantName" required>
      <br>
      <label for="plantDescription">Description: </label>
      <input type="text" id="plantDescription" v-model="newPlant.plantDescription">
      <input type="submit" value="Add" @click="handleBackToCollection()">
    </div>
    </form>
  </div>
</div>

selectedCollection是我在浏览器中点击的特定集合。

脚本:

import Firebase from 'firebase'
//firebase config here = {}
let app = Firebase.initializeApp(config);
let db = app.database();
let collectionsRef = db.ref('collections');

export default {
  firebase: {
    collections: collectionsRef
  },
  data() {
    return {
      newPlant : {
        plantDescription: "",
        plantName: "",
      }
    }
  },
  methods: {
    addPlant(sc) {
      //How do I add a new child here if I don't know the specific branch?
      this.specificCollectionRef = sc.plants;
      collectionsRef.child(this.specificCollectionRef).push(this.newPlant);
      this.newPlant.plantDescription = "";
      this.newPlant.plantName = "";
  }
}

我只包含了plantDescription和plantName来简化这一点。

JSON on Firebase:

1 个答案:

答案 0 :(得分:0)

将newPlant()中的前两行代码更改为:

this.collectionRef = sc;
collectionsRef.child(this.collectionRef['.key']).child("plants").push(this.newPlant);