Where to initialize firebase in Vue js app?

时间:2018-11-06 20:15:09

标签: javascript firebase vue.js firebase-realtime-database

  // Initialize Firebase
  var config = {
    apiKey: "...",
    authDomain: "my-project.firebaseapp.com",
    databaseURL: "https://my-project.firebaseio.com",
    projectId: "my-project",
    storageBucket: "my-project.appspot.com",
    messagingSenderId: "..."
  };
  firebase.initializeApp(config);

When I initialize Firebase in index.html or main.js, in both cases i have an error

Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

I have to initialize it in my component (Dashboard). Is it proper way to initialize firebase in one of my components? Why i can do this in e.g. main.js ?

2 个答案:

答案 0 :(得分:0)

一种方法是拥有一个firebaseConfig.js文件,如下所示:

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

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

const db = firebase.firestore();

// date issue fix according to firebase
const settings = {
    timestampsInSnapshots: true
};
db.settings(settings);

export {
    db
};

并将其导入并在每个组件(需要Firebase的地方)中使用,如下所示:

<template>
    ......
</template>
<script>
const firebase = require('../firebaseConfig.js');
export default {
  name: 'xxxxx',
  data() {
    return {
      ....
    };
  },
  methods: {
    fetchData() {
      firebase.db
        .collection('xxxxx')
        .get()
        ..... //Example of a call to the Firestore database
    }
  }
  .... 
};
</script>

答案 1 :(得分:0)

所以我发现在 index.js 目录中创建一个 firebase

然后在该文件中,您应该使用以下内容进行设置:

import firebase from "firebase/app";
import "firebase/firestore";
import 'firebase/auth';

// firebase init - add your own config here
const firebaseConfig = {
  apiKey: '',
  authDomain: '',
  databaseURL: '',
  projectId: '',
  storageBucket: '',
  messagingSenderId: '',
  appId: ''
}
firebase.initializeApp(firebaseConfig)

// utils
const db = firebase.firestore()
const auth = firebase.auth()

// collection references
const usersCollection = db.collection('users')
const postsCollection = db.collection('posts')

// export utils/refs
export {
  db,
  auth,
  usersCollection,
  postsCollection
}

然后在 main.js 里面应该是以下内容

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { auth } from './firebase'

let app
auth.onAuthStateChanged(() => {
  if (!app) {
    app = new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount('#app')
  }
})