首页 > 解决方案 > Firebase 和 Vue:如何正确初始化 firebase 和 vuefire?

问题描述

我正在尝试在我的应用程序中设置 Vuefire 和 Firebase,但在控制台中出现以下错误:

FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
    at initializeApp (webpack-internal:///./node_modules/@firebase/app/dist/index.cjs.js:377:33)
    at Object.firebase.initializeApp (webpack-internal:///./node_modules/@firebase/app/dist/index.cjs.js:667:26)
    at eval (webpack-internal:///./src/db.js:28:70)
    at Module../src/db.js (http://localhost:8080/js/about.js:323:1)
    at __webpack_require__ (http://localhost:8080/js/app.js:854:30)
    at fn (http://localhost:8080/js/app.js:151:20)
    at eval (webpack-internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/Photos.vue?vue&type=script&lang=js&:2:61)
    at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/Photos.vue?vue&type=script&lang=js& (http://localhost:8080/js/about.js:167:1)
    at __webpack_require__ (http://localhost:8080/js/app.js:854:30)
    at fn (http://localhost:8080/js/app.js:151:20)

这是我的db.js文件:

import * as firebase from 'firebase/app'
// Add the Firebase products that you want to use
import 'firebase/auth'
import 'firebase/firestore'

const firebaseConfig = {
  apiKey: 'xxx',
  authDomain: 'xxx',
  databaseURL: 'xxx',
  projectId: 'xxx',
  storageBucket: 'xxx',
  messagingSenderId: 'xxx',
  appId: 'xxx'
}

// Get a Firestore instance
export const db = firebase.initializeApp({ projectId: firebaseConfig.projectId }).firestore()
// Use Auth module
export const auth = firebase.initializeApp(firebaseConfig).auth()

// Export types that exists in Firestore
// Assuming might want to use these features later
const { Timestamp, GeoPoint } = firebase.firestore
export { Timestamp, GeoPoint }

谢谢你的帮助!

标签: javascriptfirebasevue.jsvuefire

解决方案


我让它工作了。这是我必须做的。我的困惑是认为我需要初始化 firebase/auth,但我所要做的就是在登录组件中导入 firebase 模块。

登录.vue

<script>
import firebase from 'firebase/app'
export default {
  name: 'Login',
  data() {
...snip...
  methods: {
    login() {
      const info = {
        email: this.formData.email,
        password: this.formData.password
      }
      firebase
        .auth()
        .signInWithEmailAndPassword(info.email, info.password)
        .then(
          () => {
            this.$router.push('photos')
          },
          error => {
            this.error = error.message
          }
        )
    }
  }

Photos.vue

<script>
import { db } from '@/db'
export default {
  props: ['user'],
  name: 'Photos',
  data() {
    return {
      photos: []
    }
  },
  firestore: {
    photos: db.collection('photos').orderBy('title')
  },
  methods: {
    // submitHandler(data) {
    //   // alert(`Thank you, ${data.firstname}`);
    //   db.collection("users")
    //     .add({
    //       firstname: data.firstname
    //     })
    //     .then(docRef => {
    //       console.log("Doc Id: ", docRef.id);
    //     })
    //     .catch(error => {
    //       console.error("error: ", error);
    //     });
    // }
    //     addName() {
    //   db.collection("users")
    //     .add({
    //       first: "Ada",
    //       last: "Lovelace",
    //       born: 1815
    //     })
    //     .then(function(docRef) {
    //       console.log("Document written with ID: ", docRef.id);
    //     })
    //     .catch(function(error) {
    //       console.error("Error adding document: ", error);
    //     });
    // }
  }
}
</script>

db.js

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

const firebaseConfig = {
 ..config here..
}

// firebase.initializeApp(firebaseConfig)

// Get a Firestore instance
export const db = firebase.initializeApp(firebaseConfig).firestore()

//guess I dont' need to do this here
// export const auth = firebase.initializeApp(firebaseConfig).auth()

// Export types that exists in Firestore
// Assuming might want to use these features later
const { Timestamp, GeoPoint } = firebase.firestore
export { Timestamp, GeoPoint }

对于 vuefire,我的main.js样子是这样的:

从“vue”导入 Vue

import App from "./App.vue"
import router from "./router"
import { firestorePlugin } from "vuefire"
import "bootstrap/dist/css/bootstrap.min.css"

Vue.config.productionTip = false
Vue.use(firestorePlugin)

new Vue({
    router,
    render: (h) => h(App)
}).$mount("#app")

现在,我不知道这是否是减少捆绑包大小的最佳解决方案,所以如果有人有更好的建议,请告诉我。但是,感谢您的帮助!


推荐阅读