Reputation: 2851
I'm fetching comments from the reddit API and trying to update an array with $set so it can update the view, but I get this error:
Uncaught (in promise) TypeError: $set is not a function
VM component:
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);
});
});
}
}
}
Upvotes: 3
Views: 10600
Reputation: 1259
I've set up a codepen to demonstrate the two possibilities: http://codepen.io/tuelsch/pen/YNOqYR?editors=1010
The $set method is only available on the component itself:
.then(function(response){
// Overwrite comments array directly with new data
vm.$set(vm, 'comments', response.body.data.children);
});
or, since Vue.js sould be able to trace the push call on an array:
.then(function(response){
// Clear any previous comments
vm.comments = [];
// Push new comments
response.body.data.children.forEach(function(item){
vm.comments.push(item);
});
});
See https://v2.vuejs.org/v2/api/#vm-set for the API reference.
Alternatively, you can use the global Vue.set method with the same parameters:
import Vue from 'vue';
// ...
Vue.set(vm, 'comments', response.body.data.children);
See https://v2.vuejs.org/v2/api/#Vue-set for the global API reference.
Upvotes: 3