Search code examples
firebasefirebase-realtime-databasevue.jsvuefireelement-ui

With vuejs, how do I get firebase (vuefire) object into component data


Using firebase 4.10.1 and vuefire 1.4.5.

I have confirmed that I have initialized firebase, exported a db const, and imported vuefire correctly.

I am trying to load my firebase object (JSON) onto my dataTable component data.

I am trying this:

export default {
    firebase: function () {
       return {
           fbObj: db.ref('collection')
       }
    },
    data () {
        return {
            dataTable: fbObj
        }
    }
 }

It's wired up correctly because if I use {{ fbObj }} in my template I get the JSON object displayed in full. However, if I try to load it onto the dataTable I get "fbObj is not defined" as console error.

How can I load my firebase object onto the dataTable?


Solution

  • The code:

    firebase: function () {
       return {
           fbObj: db.ref('collection')
       }
    },
    

    Creates a this.fbObj available to your Vue instance. So instead of dataTable: fbObj the correct would be more like:

    data () {
        return {
            dataTable: this.fbObj   // but even this won't work
        }
    }
    

    But that won't work. You can't do it because that data() initialization code will be executed before the fbObj has been initialized (it takes a bit of time to update it from firebase).

    So if you want dataTable to refer to that collection, either:

    • Rename the firebase object to dataTable:

      firebase: function () {
         return {
             dataTable: db.ref('collection')
         }
      },
      
    • Or create a computed property:

      firebase: function () {
         return {
             fbObj: db.ref('collection')
         }
      },
      computed: {
          dataTable() {
              return this.fbObj;
          }
      }
      

    Then you can use this.dataTable in the Vue instance JavaScript or dataTable in the template.