[Vuejs]-Vue.js / Firebase and Vuefire – Read and update a single object

0👍

The line

export const db = firebase.database()

gets executed before firebase.initializeApp(config) has finished executing, so it will be undefined.

One way to solve this is to put the initialized Firebase object on the Vue prototype:

Vue.prototype.$firebase = Firebase.initializeApp(config)

Then, inside any of your components, such as Test.vue, you can refer to the Firebase object like this:

firebase: {
  homeContent: {
    source: this.$firebase.database().ref('homeContent'),
    asObject: true
  }
},

One caveat: This only works if you create the Vue app after you know Firebase has finished initializing. You did this correctly by putting the new Vue() statement inside firebase.auth().onAuthStateChanged() in main.js, so you will be guaranteed to have an initialized Firebase object available to you at this.$firebase in any of your components.

Leave a comment