导入 firebase.firestore() returns 未定义

import firebase.firestore() returns undefined

我有一个安装了 vuefire 的 vue 应用程序。按照此处的文档:https://vuefire.vuejs.org/vuefire/getting-started.html#plugin,我有 main.js 文件:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { firestorePlugin } from 'vuefire'

Vue.config.productionTip = false;

Vue.use(firestorePlugin);

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

和 firebase.js 文件如下:

import firebase from "firebase";

const config = {
    apiKey: "XXXXXX",
    authDomain: "XXXXX",
    databaseURL: "XXXXX",
    projectId: "XXXXXXX",
    storageBucket: "XXXXXX",
    messagingSenderId: "XXXXXXX",
    appId: "XXXXX"
};

firebase.initializeApp(config);

export const db = firebase.firestore();

这是主页组件

<template>
  <div>
    <button @click="signIn">Log in with google</button>
  </div>
</template>

<script>
import firebase from "firebase";
import db from "@/firebase"
export default {
  methods: {
    signIn() {
      const provider = new firebase.auth.GoogleAuthProvider();
      firebase
        .auth()
        .signInWithPopup(provider)
        .then(result => {
          const malakas = {
            userId: result.user.uid,
            email: result.user.email,
            displayName: result.user.displayName,
            photoURL: result.user.photoURL
          };

          db.collection("malakes")
            .doc(result.user.uid)
            .set(spreadOparatorTest, { merge: true });

        })
        .catch(err => console.log(err));
    }
  }
};
</script>

<style lang="scss" scoped>
</style>

奇怪的是,在 db.collection(...) 中我得到:

TypeError: Cannot read property 'collection' of undefined

因为我正在导入的数据库被导入为未定义。但是如果我将 db.collection(...) 更改为 firebase.firestore().collection(...) 它工作正常但我不明白为什么。

问题是你需要单独导入一些依赖...这是一个很好的安全方法:

import firebase from "firebase/app";
require('firebase/firestore')
require('firebase/auth')

const config = {
    apiKey: "XXXXXX",
    authDomain: "XXXXX",
    databaseURL: "XXXXX",
    projectId: "XXXXXXX",
    storageBucket: "XXXXXX",
    messagingSenderId: "XXXXXXX",
    appId: "XXXXX"
};

firebase.initializeApp(config);

export const db = firebase.firestore();

export const auth = firebase.auth();

然后您的组件可以像这样导入 em:

import firebase from 'firebase/app'
import { db, auth } from "./firebase" // <--- or wherever the config file is
export default {
  methods: {
    signIn() {
      const provider = new firebase.auth.GoogleAuthProvider();
       auth
        .signInWithPopup(provider)
        .then(result => {
          const malakas = {
            userId: result.user.uid,
            email: result.user.email,
            displayName: result.user.displayName,
            photoURL: result.user.photoURL
          };

          db.collection("malakes")
            .doc(result.user.uid)
            .set(spreadOparatorTest, { merge: true });

        })
        .catch(err => console.log(err));
    }
  }
};

希望对您有所帮助!