Reputation: 3486
I have a simple array structured like the following:
dates[2]
0:"2018-01-09T15:00:00.000Z"
1:"2018-01-10T14:00:00.000Z"
And my watcher is set up like this:
data() {
return {
dates: [],
}
}
watch: {
// whenever dates changes, this function will run
dates: {
handler: function(before, after) {
console.log('dates is changed');
},
deep: true
}
},
The only time changes are "watched" is when a array element is added or removed, but not when the value (the time) changes.
How can I accomplish this behavior?
Upvotes: 1
Views: 52
Reputation: 56853
Due to limitations in JavaScript, Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g.
vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g. vm.items.length = newLength
To overcome caveat 1, both of the following will accomplish the same as
vm.items[indexOfItem] = newValue
, but will also trigger state updates in the reactivity system:
// Vue.set
Vue.set(example1.items, indexOfItem, newValue)
// Array.prototype.splice
example1.items.splice(indexOfItem, 1, newValue)
To deal with caveat 2, you can use splice:
example1.items.splice(newLength)
Source: https://v2.vuejs.org/v2/guide/list.html#Caveats
Upvotes: 1