Home » vue » Vue share external library with all (or most) components [duplicate]

Vue share external library with all (or most) components [duplicate]

Posted by: admin November 26, 2021 Leave a comment

Questions:

Hi I’m using Vue together with Firebase.

In my App.vue my main entry point I’m initialising the Firebase library as follows.

import Firebase from 'firebase';

export default {
    data() {
        return {
            firebase: null
        }
    },
    created() {
        this.firebase = Firebase.initializeApp({
            apiKey: "123456789",
            projectId: "projectid-1234",
        });
    }
}

Then I pass it on as a prop to other components that need it.

<template>
    <div id="app" class="container">
        <create-user-form :firebase="firebase"></create-user-form>
        <users :firebase="firebase"></users>
    </div>
</template>

In my child components I then reference Firebase using

import Firebase from 'firebase';

export default {
    props: ['firebase'],
    methods: {
        createUser() {
                this.firebase.database().ref('users')....
            }
        }
    },
    mounted() {
        this.firebase.database().ref('users')....
    }
}

The problem is that I have components that have to rely on the Firebase plugin that are 2 or 3 levels deep. Do I need to keep passing this Firebase prop on? I’m wondering if there is a more effective way?

Answers:

You can use instance properties: https://vuejs.org/v2/cookbook/adding-instance-properties.html

// In your main js file
Vue.prototype.$firebase = Firebase.initializeApp({
  apiKey: "123456789",
  projectId: "projectid-1234",
})

new Vue({
   //...
})

// In your child component
//...
this.$firebase.database().ref('users')
//...