I have a collection named people
that holds data in the form of objects:
Previous Data
[
{id: 0, name: 'Bob', age: 27},
{id: 1, name: 'Frank', age: 32},
{id: 2, name: 'Joe', age: 38}
]
This data can be modified:
New Data
[
{id: 0, name: 'Bob', age: 27},
{id: 1, name: 'Frank', age: 33},
{id: 2, name: 'Joe', age: 38}
]
Note that Frank has now become 33 years old.
I am working on an application where I want to monitor changes in the people array and log those changes when they occur:
<style>
input {
display: block;
}
</style>
<div id="app">
<input type="text" v-for="(person, index) in people" v-model="people[index].age" />
</div>
<script>
new Vue({
el: '#app',
data: {
people: [
{id: 0, name: 'Bob', age: 27},
{id: 1, name: 'Frank', age: 32},
{id: 2, name: 'Joe', age: 38}
]
},
watch: {
people: {
handler: function (val, oldVal) {
// Identify the changed object
var changed = val.filter( function( p, idx ) {
return Object.keys(p).some( function( prop ) {
return p[prop] !== oldVal[idx][prop];
})
})
// Log the change
console.log(changed)
},
deep: true
}
}
})
</script>
I referred to a recent question about comparing arrays and implemented the solution that worked fastest.
Therefore, I anticipate seeing the output:
{ id: 1, name: 'Frank', age: 33 }
However, instead of getting the expected result, all I see in the console is (keep in mind this was within a component):
[Vue warn]: Error in watcher "people"
(found in anonymous component - use the "name" option for better debugging messages.)
In the codepen link that I created, the output is an empty array rather than the specific object that underwent the change, which is not what I had anticipated.
If anyone could provide insight into why this might be happening or point out any mistakes I made, I would greatly appreciate it. Thank you!