Vue 3 comes with the Composition API built-in. It lets us extract logic easily an not have to worry about the value of this in our code. It also works better with TypeScript because the value of this no longer has to be typed.
In this article, we’ll look at how to create Vue 3 apps with the Composition API. The watch function in the Vue 3 composition API is the same as Vue 2’s this.$watch method or the watch option. Therefore, we can use it to watch for changes in reactive properties. For instance, we can write:. We watch a getter function in the 2nd argument. And we get the current and previous value in the first and 2nd parameter of the function we pass into watch as the 2nd argument. Now when we click on the increment button, we see state.count increase. If we have a primitive valued reactive property, we can pass it straight into the first argument of watch :.
And we get the same values we for count and prevCount when we click on the increment button. We can also watch multiple refs.
For instance, we can write:.
We pass in the foo and bar refs into the array.
Then we get the current and previous values from the arrays in the parameters of the function in the 2nd argument. We can also pass in the onInvalidate function into the 3rd argument.
And other behaviors are also shared with watchEffect . We can watch reactive properties with Vue 3’s composition API watchers. 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).
When watching a single ref, we simply pass it as the first argument to the watch API.