【问题标题】:Where to initialize firebase in Vue js app?在 Vue js 应用程序中在哪里初始化 firebase?
【发布时间】:2019-04-10 06:50:47
【问题描述】:
  // 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);

当我在 index.html 或 main.js 中初始化 Firebase 时,在这两种情况下我都有一个错误

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

我必须在我的组件(仪表板)中对其进行初始化。在我的一个组件中初始化firebase是否正确?为什么我可以做到这一点,例如main.js ?

【问题讨论】:

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


【解决方案1】:

一种方法是有一个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>

【讨论】:

  • 这不是每次导入时都会初始化firebase吗?
【解决方案2】:

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

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

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')
  }
})

【讨论】:

    猜你喜欢
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2023-03-13
    相关资源
    最近更新 更多