TypeError:无法在 Vue.js 中使用 Realtime Firebase 设置未定义的返回 JSON 问题的



我正在尝试使用来自实时Firebase数据库的JSON数据填充"结果"数组,但我得到

类型错误:无法设置未定义的属性"结果">

这是 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() { }而不是箭头函数会带来问题:您丢失了对this的引用(即它变得非词汇)。这意味着回调中的this不再引用 VueJS 组件本身,而是引用Window对象。

因此,将.forEach()方法中的回调更改为使用箭头函数应该可以修复遇到的错误:

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

最新更新