Vue Watch Deep

Posted on  by admin
One of the major benefits to the new Composition API in Vue 3 is how it provides a flexible and powerful reactivity system to developers.

With Vue 2, developers were reliant on the Options API to build single-file components, which enforced a level of structure to how the system was used.
The Composition API, on the other hand, gives the developer new opportunities to build reactive applications.
In a previous article, we explored the difference between ref and reactive methods.
Let's build on that understanding, and introduce two new methods from the Composition API - watch and watchEffect.
  • The Options API provided us with the watch option, which is a way to observe when values changed and perform side effects based on that.
  • Here's a basic example of what a watcher could look like with the Options API:.
  • Let's summarize what's going on here:. In our template, we have a textarea that is bound to our data value of notes.
  • In our Javascript, we have a watch key, which takes an object.
  • In that object, we have a function, also called notes.
  • This function will be automatically called whenever the value of notes changes (for example, when text is entered into the field).
  • Each watcher takes two arguments: the new value, and the previous value.
  • Since it's a function, we can do any validation or checks that need to happen here, and perform any side effects.
For further reading on watchers with the Options API, here's a link to the documentation for Vue 2.