← Home

How to Watch Nested Property or Object in Vue.js

November 11, 2019

Watchers are Vue.js feature that allows you to track a component property and run a function whenever its value changes.

The following example shows how to watch for a property in Vue.js.

Each time the input value changes, the watcher function track the property linked to the input and assigns the new value to the “result” property.

Now, let’s try to put our property in an object and see what will happen.

You notice that changes in the first input are not tracked, the problem here is that Vue.js doesn’t watch nested property directly without implementing some changes in the watcher. The solution here is to use deep watch as follow:

watch: {
    nested: {
        handle(newValue, oldValue) {
            this.result = newValue.text
        },
        deep: true
    }
}

There is also a short way to watch directly for changes in specific object property

watch: {
    'nested.text': function(newValue, oldValue) {
        this.resule = newValue
    }
}

Chafik Gharbi Full-stack web and mobile app developer with JavaScript.