Search code examples
vuejs2vuefire

Firebase Reference from Route ID


I'm trying to dynamically set the firebase reference based on the id of the URL. I'm using Vue and VueFire. Here's my code:

<template>
  <v-container>
    <h4>name: {{anObject.name}}</h4>
  </v-container>
</template>

<script>
  import Vue from 'vue'
  import db from '@/js/firebase.js'

  export default {
    props: ['id'],
    firebase: {
      anObject: {
        source: db.ref(this.getPath),
        //source: db.ref('path/id'),
        asObject: true,
        cancelCallback: function () {console.log("Cancel")},
        readyCallback: function () {console.log("Ready")}
     },
   computed: {
     getPath () {
       return 'path/' + this.id
     }
   }
 </script>

At the moment the 'anObject' object doesn't produce any data (no errors are raised). When I hard code the path (currently shown commented out) everything works as expected. I guess the problem is related to the id property not having a value at the time the 'anObject' is created? If so can I update the reference in a lifecycle hook?


Solution

  • OK I found the answer here. Basically I needed to wait for the created hook and then define the reference (noting not to define it anywhere else!).

      created () {
        this.$bindAsObject('anObject', db.ref('path/' + this.$route.params.id))
      },