0
votes

I am new to using vue-cli a webpack template I want to use firebase as my database for the vueapp i have done this to import Firebase into my app

main.js

//imported rest all required packages just dint mention here
import * as firebase from 'firebase'

let config = {
apiKey: " - XXXXXXXXCXCC",
authDomain: "XXXXXXXXX",
databaseURL: "XXXXXCCCX",
storageBucket: "XXXXXXXXXXX",
messagingSenderId: "XXXXXXXXXX"
};

firebase.initializeApp(config);

new Vue({
el: '#app',
router,
store,
render: h => h(App)
})

Now in my signup.vue file i have to import the following again

import * as firebase from 'firebase'

In order to use the following in my methods

firebase.auth().createUserWithEmailAndPassword(uEmail, uPassword).catch(function(error) {
                // Handle Errors here.
                var errorCode = error.code;
                var errorMessage = error.message;
                // ...
            });

My question is do i have to import

import * as firebase from 'firebase'

everywhere (i.e in alll vue components script tags to use firebase related methods like

firebase.auth()
firebase.database()
firebase.storage()

or can i import it at one central place and use firebase.method() in any vue component file when needed

2

2 Answers

7
votes

You could attach the firebase to the Vue.prototype:

import * as firebase from 'firebase'

let config = {
  //
}

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

new Vue({
  //
})

Then, use it to the components like this:

this.$firebase.database()
0
votes

If you want to import it just once, you can simply do in your main.js:

import * as firebase from 'firebase'

window.firebase = firebase

window object is global for webpage and it's normal practice to use it this way.