Categories
Vue 3

How to Properly Watch for Nested Data in Vue.js 3 Components?

Spread the love

Sometimes, we’ve to watch for nested data in Vue 3 components.

In this article, we’ll look at how to watch for nested data in Vue 3 components.

Adding Nested Data Watchers

To add watchers that watch nested data in reactive properties, we can set the deep option to true .

For instance, we can write:

<template>
  <div>{{ person }}</div>
</template>

<script>
export default {
  name: "App",
  watch: {
    person: {
      deep: true,
      immediate: true,
      handler(val) {
        console.log(val);
      },
    },
  },
  data() {
    return {
      person: {
        firstName: "jane",
        lastName: "smith",
      },
    };
  },
};
</script>

to watch the person object.

We set deep to true to run the handler method whenever any property in it changes.

The immediate property is set to true to the handler method to run when the person initial value is set.

Therefore, we should see the console.log method log the val value when we set the person reactive property.

Also, we can watch any single property in an object for changes.

For instance, we can write:

<template>
  <div>{{ person }}</div>
</template>

<script>
export default {
  name: "App",
  watch: {
    "person.firstName": {
      immediate: true,
      handler(val) {
        console.log(val);
      },
    },
  },
  data() {
    return {
      person: {
        firstName: "jane",
        lastName: "smith",
      },
    };
  },
};
</script>

We have the “person.firstName” watcher to watch the person.firstName value for changes.

Then the val parameter should log the value of person.firstName , which is 'jane' .

Conclusion

We can watch for nested data in reactive properties easily with watchers in Vue 3.

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 *