All Articles

How to properly watch for nested data in Vue.js

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 directly for changes to an object or an array, 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
    }
}