3

I'm new in vue.js and I'm learning vue.js from documentation and tutorial on internet, now I'm trying make app with Firebase and vue.js but my when I run it, an error says:

-firebase not defined

However, I'm pretty sure that I imported it. Here my code:

main.js:

import Vue from 'vue'
import App from './App'
import router from './router'
import * as firebase from "firebase"

var config = {
 apiKey: "###########",
 authDomain: "###########",
 databaseURL: "###########",
 projectId: "###########",
 storageBucket: "###########",
 messagingSenderId: "###########"
};
 firebase.initializeApp(config);
 Vue.config.productionTip = false
 /* eslint-disable no-new */
 new Vue({
  el: '#app',
  router,
  firebase,
  components: { App },
  template: '<App/>'
 })

This my component register:

<template>
<div class="login">
    <h3>Lets Register</h3>
    <input type="email" v-model="email">
    <input type="password" v-model="password">
    <button v-on:click="register">Submit</button>
    <p><router-link to="/Login"> Login? </router-link></p>
</div>

<script>
     export default {
     name: 'Register',
     data () {
        return{
            email: '',
            password: ''
        }
      },
     methods:{
        register : function(){
            firebase.auth().createUserWithEmailAndPassword(this.email,this.password).then(
                function (user) {
                    alert('Account been created')
            },
            function(err){
                alert('opps'+ err.message)
            }
                );
            }
        }
    }

Any help would be appreciated.

4 Answers 4

2

In main.js just register firebase as global with Vue.use(firebase) like this, and all components can access that.

import firebase from 'firebase'
Vue.use(firebase) 

var config = {
 apiKey: "####",
 authDomain: "####",
 databaseURL: "####",
 projectId: "####",
 storageBucket: "####",
 messagingSenderId: "####"
};
firebase.initializeApp(config);

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

And in your components don't forget to import that like this:

import firebase from 'firebase'
Sign up to request clarification or add additional context in comments.

Comments

1

It's really undefined at your component, I have with this problem too. How to solve it? Modules.

Create a Js file called firebase.service.js, on this file you'll define every function that uses firebase, you'll configure the firebase at this file too, then you'll export the functions to the other files, where you'll import and use them, just like this:

firebase.service.js

import * as firebase from 'firebase'

var config = { // put here your credentials
  apiKey: apiKey,
  authDomain: authDomain,
  databaseURL: databaseURL,
  projectId: projectId,
  storageBucket: storageBucket,
  messagingSenderId: messagingSenderId
}

firebase.initializeApp(config)

var auth = firebase.auth()
var db = firebase.database()

export function signOut (callback) {
  auth.signOut().then(value => {
    callback()
  }, err => { callback(err) })
}

Components

<script>
    import { signOut } from './firebase.services'

    // use it here

</script>

You can't export firebase itself, because it'll throw an error saying that the firebase was already initialized.

2 Comments

sory sir but i din't use vuex yet
Done. If you what to see this idea in practice, take a look at this repo: link. I can help you with firebase + Vue, I wasted a lot of time using it.
1

You should import firebase in every component you want to use it in. Looks like you are importing firebase now in a different file so just add the import to the component.

2 Comments

but when i imported it on component is saya vue not defined
It'll not work, you can't export/import the firebase already configurated, it'll raise an error.
1

Just adding some more info in case someone finds it useful. First off, only load components of firebase that you need. Gabriel Carneiro's response is really the base of the following...

Your firebase.js where you initialize and export your methods, modules, etc

/*this will import all the firebase which can be a bottleneck */
// import * as firebase from 'firebase'

/*better only importing what you need*/
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';

const config = {
    apiKey: "***************",
    authDomain: "***************",
    databaseURL: "***************",
    projectId: "***************",
    storageBucket: "***************",
    messagingSenderId: "***************",
    appId: "***************"
};

/*OptionalPrjName is optional that you can initialize your firebase with 
it in case you are using more than one project or config file  , 
it's optional as firebase can initialize without this name*/
firebase.initializeApp(config, "OptionalPrjName");
const auth = firebase.auth(firebase.app("OptionalPrjName"));
const firestore = firebase.firestore(firebase.app("OptionalPrjName"));
const functions = firebase.functions(firebase.app("OptionalPrjName"));

/*create modules ; say one for sign up , etc , another for functions, etc ... */
const app_firebase = {
    signout: () => console.log(`firebase is` , firebase),
    test: () => console.log(`testing`),
}

/*export them here so you can import them individually where you need in your components */
export {
    app_firebase,
}

/*another way of only exporting your functions, etc. I like the above better becuase it helps bundling similar 
functionalities together under a name space ; make sure you don't create confusion by assigning similar naming 
so I always add something like app_ to my names in the above exports*/
export function fire_auth(callback) {
    console.log(`firebase `, auth, firestore, functions);
}

your component, in which you can only import what you need to use (let call the component signup.vue) and say we have placed in the root of our directory so we access it in views like ../firebase :

<template>
    <div class="signup">
        <h2>signup</h2>
        <button type="button" @click="signup">Sign Up</button>
        <router-link to="/login">Login</router-link>
    </div>
</template>
<script>

import { fire_auth, app_firebase } from '../firebase';

export default {
    name: 'signup',
    data() {
        return {}
    },
    methods: {
        signup: function() {
            fire_auth();
            app_firebase.test();
        }
    }
}
</script>
<style scoped>
/* scoped attr limits style to this component only */
</style>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.