使用 Vue JS 2,firebase 返回的数据对象未在实例上定义,但在渲染期间被引用
2017-12-29
1068
我正在学习 https://medium.com/codingthesmartway-com-blog/vue-js-2-firebase-e4b2479e35a8 上的 Vue 教程。我可以将新数据发布到 firebase,但没有收到任何返回的数据。
我在控制台中看到此错误:
vue.esm.js?efeb:578
[Vue warn]: Property or method "books" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties .
相关块如下。这是用于显示检索到的数据的模板循环:
<tr v-for="(book, key) in books" v-bind:key="key">
<td>
{{book.title}}
</td>
</tr>
在脚本部分:
import Firebase from 'firebase'
let config = {
apiKey: "...",
authDomain: "...",
databaseURL: "https://...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
};
let app = Firebase.initializeApp(config)
let db = app.database()
let booksRef = db.ref('books/')
/* was
export default {
name: 'app',
firebase: {
books: booksRef
},
*/
export default {
name: 'app',
firebase: function () {
return {
books: db.ref('books/')
}
},
data() {
return {
newBook: {
title: '',
author: '',
}
}
},
methods: {
addBook: function() {
// code here
},
removeBook: function(book) {
// code here
}
}
}
任何建议都将不胜感激!
2个回答
由于 Vue 不允许动态添加根级反应性属性,因此您必须通过预先声明所有根级反应性数据属性(即使值为空)来初始化 Vue 实例:
data () {
return {
newBook: {
title: '',
author: '',
},
books: '',
}
},
alxvrz
2019-06-19
来自 vuefire 文档 :
If you need to access properties from the Vue instance, use the function syntax:
var vm = new Vue({
el: '#demo',
firebase: function () {
return {
anArray: db.ref('url/to/my/collection/')
}
}
})
Soleno
2017-12-29