Reputation: 128
I need to get object properties change inside the array. For to do that, I'm using vue.$watch. I read the documentation but I didn't get that.
The scenario is:
...
data() {
return {
Questions: [{foo: 1}, {foo: 2}, {foo: 3}]
}
},
...
this.$watch("Questions", function (newVal, oldVal) {
// something...
}, { deep: true });
UPDATED
The solution is here!
Upvotes: 0
Views: 662
Reputation: 4786
There is a Javascript limitation - if you change array elements directly (e.g. this.array[0].foo = 'bar'
), Vue cannot track these changes, hence the watcher will not be triggered.
It will be triggered though if you use any of Array.prototype
functions, like push
, pop
or will re-assign array.
So the most basic solution will look this way:
change: function () {
let questions = this.Questions;
questions[0].foo = 5;
this.Questions = questions;
/* or
let index = 0;
let question = this.Questions[index];
question.foo = 5;
this.Questions.splice(index, 1, question);
*/
}
Updated jsFiddle: here
Stuff to check out: Arrays reactivity in Vue.js
Upvotes: 2