When watching an array in Vue like this:
watch: {
myarray(val) {
// react to additions or deletions on myarray
},
},
and adding or removing items on that array like this:
this.myarray.splice(this.myarray.findIndex((d) => d.id === myId), 1);
this.myarray.push({name: 'New Item'});
how do I watch for these additions or deletions on the array. Two ways I could do this:
- Use v-for to generate (renderless) components and use the created()/beforeDestroy() hooks of this component.
- Compare the old to the new version of the array and find differences (by iterating over the whole array)
But both methods would add a performance overhead to my application (There are up to a hundred thousand elements in this array).
Is there any way the watch callback can pass me a list of additions or deletions.
The (value, mutation) callback described here: https://optimizely.github.io/vuejs.org/api/instance-methods.html would be exactly what I need. Unfortunately that doesn't seem to work anymore.
Vue.set(...)orvm.$set(...)for adding one element, usesVue.delete(...)orvm.$delete(...)to delete one element.isArrayDeleted,indexOfArrayDeletedetc. from the parent component.