Composition Api Watch

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.

Boussadjra Brahim

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).

Boussadjra BrahimBoussadjra Brahim

For further reading on watchers with the Options API, here's a link to the documentation for Vue 2.

  1. Now that we have a basic understanding of watchers in the Options API, let's dive into the Composition API!
  1. The Composition API provides us with two different methods to handle side effects - watch and watchEffect.
Just like with ref and reactive, these methods are not meant to compete with each other, but to be used as required by the application.

Not the answer you're looking for? Browse other questions tagged vue.jsvuejs3vue-composition-apivue-props or ask your own question.