在 Vue js 应用程序中在哪里初始化 firebase?

Posted

技术标签:

【中文标题】在 Vue js 应用程序中在哪里初始化 firebase?【英文标题】:Where to initialize firebase in Vue js app? 【发布时间】: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 ?

【问题讨论】:

类似问题:***.com/questions/53139432/… 【参考方案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')
  
)

【讨论】:

以上是关于在 Vue js 应用程序中在哪里初始化 firebase?的主要内容,如果未能解决你的问题,请参考以下文章

Express.js 项目中在哪里进行验证——在数据库层进行验证(re. Mongoose)?

在同构 Redux 应用程序中在哪里设置 cookie?

使用复制列表初始化从函数返回,不需要复制/移动构造函数 - C++ 11 标准中在哪里说明?

vue中在当前页面跳转当前页面,解决页面初始化数据的问题

vue创建项目初始化及基本配置

Vue.js 在哪里?