Vue.js + Firestore 无法读取未定义的 属性 'collection'

Vue.js + Firestore Cannot read property 'collection' of undefined

我最近一直在玩 Vue.jsFirestore,我发现了一个很棒的插件,让我的生活更轻松,尽管它涉及的代码更少 link到我的 firestore 数据库,undefined 错误让我的生活变得非常困难。

我的很简单:

App.vue:

<template>
  <div id="app">
    <Projects></Projects>
  </div>
</template>

<script>

import Projects from './Projects';
export default {
  name: 'app',

  components: {
    Projects
  },
  data() {
    return {}
  }
}
</script>
<style></style>

Projects.vue:

<template>
  <div id="projects">
    <h1>Hi</h1>
    <p v-for="project in projects" :key="project.project_id">{{ project.title }}</p>
  </div>
</template>

<script>

import db from './main'

export default {
  name: 'projects',
  data() {
    return {
      projects: [],
    }
  },
  firestore: {
    projects: db.collection('projects')
  }
}
</script>
<style></style>

Main.js:

import 'babel-polyfill';
import Vue from 'vue'
import App from './App.vue'

// Firebase Imports
import Firebase from 'firebase/app'
import 'firebase/firestore'
import { firestorePlugin } from 'vuefire'

// Use Plugins
Vue.use(firestorePlugin)

// Initialize Firebase Configuration
var firebaseConfig = {
  apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
  authDomain: "xxxxxxxxxxxx.firebaseapp.com",
  databaseURL: "https://xxxxxxxxxxxx.firebaseio.com",
  projectId: "xxxxxxxxxxxx",
  storageBucket: "xxxxxxxxxxxx.appspot.com",
  messagingSenderId: "xxxxxxxxxxxx",
  appId: "xxxxxxxxxxxx"
}

const firebaseApp = Firebase.initializeApp(firebaseConfig)
export const db = firebaseApp.firestore()

new Vue({
  el: '#app',
  render: h => h(App)
})

当我 运行 这个应用程序时,我的控制台出现以下错误:

Uncaught TypeError: Cannot read property 'collection' of undefined
    at eval (Projects.vue?8816:20)
    at Object.<anonymous> (build.js:1640)
    at __webpack_require__ (build.js:679)
    at fn (build.js:89)
    at eval (Projects.vue?eb12:1)
    at Object.<anonymous> (build.js:3128)
    at __webpack_require__ (build.js:679)
    at fn (build.js:89)
    at eval (145:1)
    at Object.<anonymous> (build.js:1633)

如果有人对此有经验并且可以阐明为什么我在我的代码中是个大笨蛋,那将不胜感激!

所以在玩了一会儿代码之后,我终于修复了它,同时也摆脱了过程中的其他警告。

更新了 vuefire 初始化:

Vue.use(firestorePlugin)
firebase.initializeApp({
  apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
  authDomain: "xxxxxxxxxxxx.firebaseapp.com",
  databaseURL: "https://xxxxxxxxxxxx.firebaseio.com",
  projectId: "xxxxxxxxxxxx",
  storageBucket: "xxxxxxxxxxxx.appspot.com",
  messagingSenderId: "xxxxxxxxxxxx",
  appId: "xxxxxxxxxxxx"
});

export const db = firebase.firestore()

已更新Projects.vue:

import { db } from './main'

export default {
  name: 'projects',
  data() {
    return {
      projects: [],
    }
  },
  firestore() {
    return {
      projects: db.collection('projects')
    }
  }
}

这里那里的小改动最终解决了我的问题,我希望这能帮助遇到这个问题的其他人:)