I'm fetching ments 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 ponent:
export default {
name: 'top-header',
ponents: {
Comment
},
data () {
return {
username: '',
ments: []
}
},
methods: {
fetchData: function(username){
var vm = this;
this.$http.get(`/${username}/ments.json?jsonp=`)
.then(function(response){
response.body.data.children.forEach(function(item, idx){
vmments.$set(idx, item);
});
});
}
}
}
I'm fetching ments 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 ponent:
export default {
name: 'top-header',
ponents: {
Comment
},
data () {
return {
username: '',
ments: []
}
},
methods: {
fetchData: function(username){
var vm = this;
this.$http.get(`https://www.reddit./user/${username}/ments.json?jsonp=`)
.then(function(response){
response.body.data.children.forEach(function(item, idx){
vm.ments.$set(idx, item);
});
});
}
}
}
Share
Improve this question
asked Feb 7, 2017 at 17:06
frostyfrosty
2,8516 gold badges42 silver badges66 bronze badges
1 Answer
Reset to default 3I'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 ponent itself:
.then(function(response){
// Overwrite ments array directly with new data
vm.$set(vm, 'ments', 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 ments
vm.ments = [];
// Push new ments
response.body.data.children.forEach(function(item){
vm.ments.push(item);
});
});
See https://v2.vuejs/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, 'ments', response.body.data.children);
See https://v2.vuejs/v2/api/#Vue-set for the global API reference.