Categories
Vue Answers

How to Deep Watch an Array of Objects and Calculating the Change with Vue.js?

Spread the love

Sometimes, we want to deep watch an array of objects and calculating the change with Vue.js.

In this article, we’ll look at how to deep watch an array of objects and calculating the change with Vue.js.

Deep Watch an Array of Objects and Calculating the Change with Vue.js

We can deep watch an array of objects and calculate the change with Vue.js with watchers.

For instance, we can write:

App.vue

<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>

Person.vue

<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 App.vue , we have the people array that’s used to render the Person component with v-for .

We pass in the person as the value of the person prop.

Then in Person , we add the props property to accept the person prop.

And we have the p reactive property which we set to the copy of person as its value in the mounted hook.

In the p watcher in the watch property, we log the newValue value.

We set the deep option to true to let us watch for changes in objects.

And in the template, we render p.name and bind p.age as to the input value of the text input.

Now when we type into the text input, the p watcher should run and log the newValue.age value.

Conclusion

We can deep watch an array of objects and calculate the change with Vue.js with watchers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *