[Vuejs]-Firebase .on with Vue without using Vuefire

0👍

In case anyone else is looking to use Firebase in Vue without Vuefire.

Do check out this video!

Vue 2 & Vuex & Firebase Tutorial – Getting It All Working Together

https://youtu.be/niPgyv53x8c

2👍

At first, always the best option is to use VueFire if you need to use Vue.js and Firebase.

However, if you want to use Vue.js without Vuefire, you can set up the firebase instance in mounted section in your component. Vue component’s lifecycle is not the same as the one without Vue, so you better to use lifecycle handler provided by Vue.

Vue.component("YourComponent", {
  ...

  mounted() {
    firebase.initializeApp({
      apiKey: "apiKey",,
      databaseURL: "https://databaseName.firebaseio.com"
    });

    const database = firebase.database();

    database.ref('/users/100').once('value').then((snapshot) => {
      // Do your business
    });

    ...

    //
    // You can also set up more handlers like above...
    //
  },

  ...
});

However, if you want to use two-way binding, it is a little tough. The good point of Vuefire is its easy mixin of Vue component data structure and Firebase instance.

Without Vuefire, the code I can think up would be like this

Vue.component("YourComponent", {
  ...

  data() {
    return {
      users: []
    };
  },

  ...

  mounted() {

    //
    // Initialize Firebase SDK and get `database` to use below.
    //

    ...

    database.ref('/users').on('value', (snapshot) => {
      // By using arrow function, the context of `this` here is binded
      // into the current component data `users`.
      this.users = snapshot.val();
    });  
  },

  ...
});

Leave a comment