Categories
Vue Answers

How to Watch a Deeply Nested Object with Vue.js?

Spread the love

Sometimes, we want to watch a deeply nested object with Vue.js.

In this article, we’ll look at how to watch a deeply nested object with Vue.js.

Watch a Deeply Nested Object with Vue.js

To watch a deeply nested object with Vue.js, we can add a watcher for the nested property.

To do this, we write:

<template>  
  <div id="app">  
    <input type="checkbox" v-model="block.checkbox.active" />  
  </div>  
</template>  
<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      block: {  
        checkbox: {  
          active: false,  
        },  
        someOtherProp: {  
          changeme: 0,  
        },  
      },  
    };  
  },  
  watch: {  
    "block.checkbox.active": {  
      immediate: true,  
      handler(val) {  
        console.log(val);  
      },  
    },  
  },  
};  
</script>

We have the block reactive property.

And we want to watch for changes to the block.checkbox.active property.

To do that, we add the 'block.checkbox.active' watcher object.

We set immediate to true to watch the initial value.

And we have the handler method that has the val parameter that has the current value of block.checkbox.active .

We set v-model to block.checkbox.active to bind the checkbox value to the block.checkbox.active property.

Conclusion

To watch a deeply nested object with Vue.js, we can add a watcher for the nested property.

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 *