⚠️ This lesson is retired and might contain outdated information.

Watch for Changes in Vue Using the @Watch Decorator with TypeScript

Share this video with your friends

Social Share Links

Send Tweet

Vue watchers allow to perform async updates as a side effect of a property change. This lesson shows you how you can watch properties on your class based component and how to use the @Watch decorator for it.

[00:00] This example uses a count variable that we will watch for changes. For that, we need to import the watch decorator from vue-property-decorator, and then we'll write @watch and the name of the variable, in this case count.

[00:16] Then write a method that takes the new as the first parameter and the old value as the second. Let's just write a console.log for it, and then let's try it. When we click the button, we see those values logged in the console.

[00:37] Let's try another example. Imagine instead of a number variable, we have an object with an accumulator variable inside. Let's change the count in the template, and in the sum up method. When we click the button now, we see the number is changing, but the watch is not triggered.

[01:00] This is because we are not changing the object itself. We are changing a property inside. If we change this, and we replace the object with a new one, when we try now, even if the counter doesn't sum up, we see that the watch is triggered.

[01:18] How can we deep watch an object? The watch decorator takes an optional object as a second parameter where we can specify deep true in order to deep watch an object. Now, we can change the sum up method back, and when we try this, we see that it is working, and the watch count method is triggered.