[Vuejs]-Make a variable available to all Vue components without explicitly passing it by props?

1👍

You can create a wrapper plugin for any module (ie. firebase in this case).

/plugins/firebase-wrapper.js

import firebase from 'firebase'

const FirebaseWrapper = {
  install (Vue) {
    // INSTALL
    if (this.installed) return
    this.installed = true

    // CONFIG
    const config = {
     apiKey: "",
     authDomain: "",
     databaseURL: "",
     projectId: "",
     storageBucket: "",
     messagingSenderId: ""
    }

    // INIT
    firebase.initializeApp(config)

    Vue.prototype.$firebase = firebase
    Vue.firebase = firebase
  }
}

export default FirebaseWrapper

main.js

import FirebaseWrapper from "./plugins/firebase-wrapper.js"
Vue.use(FirebaseWrapper)

Access firebase APIs from a .vue file like below

let currentUser = await this.$firebase.auth().currentUser

Or

import Vue from 'vue'
let currentUser = await Vue.firebase.auth().currentUser

vuefire (npm module) possibly will do the same for you, ie. will create a wrapper plugin & will make firebase APIs globally available, so you won’t have to write your own custom plugin.

Leave a comment