Javascript Vue.js:Uncaught(承诺中)TypeError:$set不是函数
我正在从reddit API获取注释,并尝试使用$set更新数组,以便它可以更新视图,但我遇到以下错误:Javascript Vue.js:Uncaught(承诺中)TypeError:$set不是函数,javascript,vue.js,Javascript,Vue.js,我正在从reddit API获取注释,并尝试使用$set更新数组,以便它可以更新视图,但我遇到以下错误: Uncaught(in promise)TypeError:$set不是函数 虚拟机组件: export default { name: 'top-header', components: { Comment }, data () { return { username: '', comments: [] } },
Uncaught(in promise)TypeError:$set不是函数
虚拟机组件:
export default {
name: 'top-header',
components: {
Comment
},
data () {
return {
username: '',
comments: []
}
},
methods: {
fetchData: function(username){
var vm = this;
this.$http.get(`https://www.reddit.com/user/${username}/comments.json?jsonp=`)
.then(function(response){
response.body.data.children.forEach(function(item, idx){
vm.comments.$set(idx, item);
});
});
}
}
}
我已经设置了一个代码笔来演示两种可能性: $set方法仅在组件本身上可用:
.then(function(response){
// Overwrite comments array directly with new data
vm.$set(vm, 'comments', response.body.data.children);
});
或者,由于Vue.js应该能够跟踪阵列上的推送调用:
.then(function(response){
// Clear any previous comments
vm.comments = [];
// Push new comments
response.body.data.children.forEach(function(item){
vm.comments.push(item);
});
});
有关API参考,请参阅
或者,您可以使用具有相同参数的global Vue.set方法:
import Vue from 'vue';
// ...
Vue.set(vm, 'comments', response.body.data.children);
请参阅以获取全局API参考。它正在提供
ReferenceError:未定义注释
我在案例中进行了编辑,但它仍然没有更新视图。我正在做一个v-for
来打印它们,它不会更新。对不起,完全忽略了注释是一个数组。我推荐推送版本。