简体   繁体   中英

Adding a new child to a real-time Firebase database using Vue

Template:

<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 is a specific collection I have clicked on in the browser.

Script:

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 = "";
  }
}

I only included plantDescription and plantName to simplify this a little more.

Firebase上的JSON:

Change the first two lines of code in newPlant() to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM