0

我有一个安装了 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:无法读取未定义的属性“集合”

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

4

1 回答 1

3

问题是您需要分别导入一些依赖项......这是一个很好的安全方法:

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

希望这可以帮助!

于 2019-06-29T14:17:37.317 回答