我正在从 reddit API 获取评论并尝试使用 $set 更新数组以便它可以更新 View ,但我收到此错误:
未捕获( 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);
});
});
}
}
}
最佳答案
我已经设置了一个代码笔来演示这两种可能性:http://codepen.io/tuelsch/pen/YNOqYR?editors=1010
$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);
});
});
参见 https://v2.vuejs.org/v2/api/#vm-set用于 API 引用。
或者,您可以使用具有相同参数的全局 Vue.set 方法:
import Vue from 'vue';
// ...
Vue.set(vm, 'comments', response.body.data.children);
参见 https://v2.vuejs.org/v2/api/#Vue-set用于全局 API 引用。
关于javascript - Vue.js:未捕获( promise )TypeError:$set 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42095831/