Karol Makara
Karol Makara

Reputation: 35

Make a variable available to all Vue components without explicitly passing it by props?

I have a question, so in react we have react consumer and provider, that let pass variables wherever i want. Does Vue has something like that? I need pass my Firebase class to almost every component, so pass it through props is a bad idea.

Upvotes: 0

Views: 286

Answers (1)

Shivam Singh
Shivam Singh

Reputation: 1731

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.

Upvotes: 1

Related Questions