[英]Uncaught TypeError: Cannot set property 'app' of undefined Vue.js
[英]TypeError: Cannot set property of undefined returned JSON issue using Realtime Firebase in Vue.js
我正在尝试使用来自实时 Firebase 数据库的 JSON 数据填充“结果”数组,但我得到了
TypeError:无法设置未定义的属性“结果”
这是 VueJs 代码。
<template>
<div id="show-results">
<h1>Data</h1>
<input type="text" v-model="search" placeholder="search results" />
<div v-for="result in results" class="single-result">
<h2>{{ result.Speed }}</h2>
<article>{{ result.DiscManufacturer }}</article>
</div>
</div>
</template>
<script>
import db from '@/firebase/init'
import firebase from 'firebase'
export default {
data () {
return {
results: [
],
search: ''
}
},
methods: {
}, created() {
firebase.database().ref().on('value', (snapshot) => { snapshot.forEach((childSnapshot) => { this.results = JSON.stringify(childSnapshot.val());
console.log(this.results);
});
}
</script>
请帮忙。 我是 VueJS 的初学者。
您的问题来自在.forEach()
方法中使用function() { }
而不是箭头 function :您正在失去this
的引用(即它变得非词法)。 这意味着您的回调中的this
不再是指 VueJS 组件本身,而是指Window
object。
因此,将.forEach()
方法中的回调更改为使用箭头 function 应该可以解决您遇到的错误:
snapshot.forEach(childSnapshot => {
this.results = childSnapshot.val();
});
专业提示:由于您的回调包含一行,因此您可以通过不使用大括号使其更具可读性:
snapshot.forEach(childSnapshot => this.results = childSnapshot.val());
看起来this
不是您的 Vue 实例。
尝试this
绑定到您的forEach
。
snapshot.forEach(function(childSnapshot){
this.results = childSnapshot.val();
}.bind(this));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.