Mastering Deep Watching of Object Arrays in Vue.js
Written on
Chapter 1: Understanding Deep Watching
In certain scenarios, it's necessary to closely monitor changes in an array of objects using Vue.js. This article will guide you through the process of deep watching an array of objects and calculating the changes that occur.
Deep Watching Objects with Vue.js
To effectively deep watch an array of objects and track changes, we can utilize Vue's watchers. Below is an example of how to implement this in a Vue component:
<template>
<div id="app">
<Person :person="person" v-for="person in people" :key="person.id"></Person></div>
</template>
<script>
import Person from "@/components/Person";
export default {
name: "App",
components: {
Person,},
data() {
return {
people: [
{ id: 0, name: "Bob", age: 27 },
{ id: 1, name: "Frank", age: 32 },
{ id: 2, name: "Joe", age: 38 },
],
};
},
};
</script>
In the App.vue component, we maintain an array called people, which is used to render the Person component with the v-for directive. The person prop is passed to each Person instance.
Inside the Person.vue component, we define the following:
<template>
<div class="hello">
<div class="person">
{{ p.name }}
<input type="text" v-model="p.age" />
</div>
</div>
</template>
<script>
export default {
name: "Person",
props: {
person: Object,},
data() {
return {
p: {},};
},
watch: {
p: {
handler(newValue) {
console.log(newValue.id);
console.log(newValue.age);
},
deep: true,
},
},
mounted() {
this.p = { ...this.person };},
};
</script>
In Person.vue, we define a props property to accept the person prop. The reactive p property is initialized with a copy of the person object in the mounted lifecycle hook. The watcher on p is set to observe changes deeply, allowing us to log the new values whenever a change occurs.
When users input a new age in the text field, the watcher is triggered, and the updated age is logged to the console.
The first video titled "Vue JS 3 Tutorial - 28 - Immediate and Deep Watchers" dives deeper into using watchers effectively in Vue.js applications.
Conclusion
By implementing Vue's watchers, we can effectively deep watch an array of objects and track changes in real-time. For more insights, visit PlainEnglish.io.
Additionally, check out the video "React Table Tutorial (TanStack Table)" for an exploration of data handling in React applications.