Firebase和Vue:如何正确初始化Firebase和vuefire?

时间:2020-06-06 11:03:44

标签: javascript firebase vue.js 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 }

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我知道了。这就是我要做的。 我的困惑是,我需要初始化firebase / auth,但是我要做的就是在登录组件中导入firebase模块。

Login.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")

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