boomboxboy
boomboxboy

Reputation: 2434

Using firebase in vuejs2 app via vue-cli(webpack)

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

Upvotes: 0

Views: 972

Answers (2)

pespantelis
pespantelis

Reputation: 15372

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()

Upvotes: 7

euvl
euvl

Reputation: 4786

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.

Upvotes: 0

Related Questions