Home > Enterprise >  How do I initialize firebase within a Vue3 component?
How do I initialize firebase within a Vue3 component?

Time:03-19

My firebaseConfig.js file located in the src directory alongside main.js

import * as firebase from 'firebase/app';
import 'firebase/firestore';

const firebaseConfig = {
  apiKey: "AIzaSyC61LOwmDxIqSr9KpVqRFpuDJNuhNSGT3U",
  authDomain: "vue-social-logins.firebaseapp.com",
  projectId: "vue-social-logins",
  storageBucket: "vue-social-logins.appspot.com",
  messagingSenderId: "11471906314",
  appId: "1:11471906314:web:88f56d6e710b443453a1f3",
  measurementId: "G-R855W28FHP"
};

export const firebaseApp = firebase.initializeApp(firebaseConfig, 'vue-social-logins');

console.log(firebase);
console.log(firebaseApp);

My component file SocialLogin.vue located in the src/components folder

<template>
  <div >
    <h1>{{ msg }}</h1>
    <button @click="handleSignIn">login</button>
  </div>
</template>

<script>
require('../firebaseConfig.js');
import firebase from 'firebase/app';
import { onMounted } from 'vue';
import firebaseApp from '../firebaseConfig.js';

export default {
  name: 'SocialLogin',
  props: {
    msg: String
  },
  setup() {
    
    onMounted(() => {
      console.log('on mount');
      console.log('firebase2: '   firebase);
      console.log('firebaseApp: '   firebaseApp);
    });
  }
}
</script>

<style scoped>
</style>

The console.log(firebase) and console.log(firebaseApp) from the firebaseConfig.js file works great and the data is correctly propagated. However, the console.log('firebase2: ' firebase); and console.log('firebaseApp: ' firebaseApp); from the SocialLogin.vue component file log as 'undefined' for both. How do I get firebase to correctly initialize in my component files as well? I'm trying to implement Google login via firebase for my Vue3 app but keep getting stuck on this step.

CodePudding user response:

In firebaseConfig.js use export default instead of export const.

And in src/components/SocialLogin.vue, use import firebaseApp from '../firebaseConfig.js'

  • Related