Vue Deep Watch

Posted on  by admin
The watch API is part of the larger Vue Composition APIs.

It takes a data source and a callback function that executes when the provided data changes.
In my experience, I’ve found that whenever I need to track reactive data and perform some operation when the data changes, computed properties were all I needed.
However, like the Options API, the Vue Composition API also shipped with watch, that offers developers another way of watching and reacting to data changes.
I have found that there’s some nuance around it and I wanted to deep dive into it in this post and shine more light on the different ways you can use it.
  • This is largely because it behaves differently depending on the type of data you’re watching, and it can get confusing if you’re not already familiar with it.
  • In this post, we’ll look at how to use it when dealing with ref and reactive states as well as with arrays and objects.
  • A general rule of thumb when working with the watch API is to know that it takes two arguments.
  • The first is the data source you want to watch and the second is a callback function that applies side effects to that data.
  • The examples that will follow is based on simple data types like: numbers, strings booleans.
  • You can skip to examples on complex data types (arrays and objects).
  • The watch API allows us to watch a single ref or to collectively watch multiples refs.
  • Let's demonstrate how to watch a single ref with simple data types (strings, numbers booleans).
Here’s a quick example:. This is fairly straightforward. We are watching name to ensure that when its value changes, we perform any operation we want in the callback.