How to usedeep: true Option in Vue

In this approach, we are using the deep: true option in the watcher to properly watch changes within the nested Data Structures. This makes sure that the changes to the deeply nested properties like user.name, trigger the handler function.

Syntax:

new Vue({
watch: {
'nestedDataProperty': {
handler: function(newValue, oldValue) {
// Tasks
},
deep: true
}
}
});

Example: Below is the implementation of the above-discussed approach.

HTML




<!DOCTYPE html>
 
<head>
    <title>Example 1</title>
    <script src=
"https://cdn.jsdelivr.net/npm/vue@2">
      </script>
</head>
 
<body>
    <div id="app">
        <h1 style="color:green">
            w3wiki</h1>
        <h3>Approach 1: Using deep:true Option</h3>
        <p>Name: {{ user.name }}</p>
        <p>Age: {{ user.age }}</p>
        <input v-model="newName"
               placeholder="Enter new name">
        <button @click="changeName">Update Name</button>
        <p v-if="dataChanged" style="color: green;">
              Data has changed!
          </p>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                user: {
                    name: 'GFG USER',
                    age: 23
                },
                newName: '',
                dataChanged: false
            },
            watch: {
                user: {
                    handler: function (newValue, oldValue) {
                        console.log('User data is changed!', newValue);
                        this.dataChanged = true;
                    },
                    deep: true
                }
            },
            methods: {
                changeName: function () {
                    this.user.name = this.newName;
                    this.newName = '';
                    this.dataChanged = false;
                }
            }
        });
    </script>
</body>
 
</html>


Output:

How to Properly Watch for Nested Data in VueJS ?

In Vue.js, we can watch the nested data to properly control the changes within the nested properties. In this article, we will explore both of the approaches with the practical implementation of these approaches in terms of examples and outputs.

We can watch this by using two different approaches:

Table of Content

  • Using deep: true Option
  • Using Computed Property

Similar Reads

Approach 1: Using deep: true Option

In this approach, we are using the deep: true option in the watcher to properly watch changes within the nested Data Structures. This makes sure that the changes to the deeply nested properties like user.name, trigger the handler function....

Approach 2: Using Computed Property

...