So I have been learning the Vue Composition API and was wondering what the difference between watchEffect
and watch
is. Watch says it's the same as the Vue 2 watch, so I'm guessing watchEffect is like the 2.0 of that? I'm wondering if there is any specific cases where one would have great advantages over the other like in the case of stopping the watchEffect and then reactivating it instead of using a boolean in a regular watch... or are they just basically different ways of writing the same thing.
Thanks!
Reference:
watcheffect: https://vue-composition-api-rfc.netlify.com/api.html#watcheffect
watch: https://vue-composition-api-rfc.netlify.com/api.html#watch
Find answer to this question in the following article and discover the benefits of Composition API. Vue 3 introduced a new approach to creating components called Composition API . It is an alternative to the Options API . The Composition API is fully optional and you don't need to use it if you want to use Vue 3.
A watchers provide Vue Js users the ability to produce side effect in reaction to a change in state in one or more reactive variables. Watch are very similar to computed properties as they are both defined as a feature that allows the user to “watch” for a property or data change.
Vue 3 introduced Composition API which allows developers to write components in a better way. Using this API, developers can group the logical pieces of code together, which in turn helps write readable code. Composition API is a built in feature in Vue 3 and is also available in Vue 2 via @vue/composition-api plugin.
If you are on a very large and complex existing project using Vue 2: You may not want to migrate to Vue 3, depending on your code, the migration time and performance benefits may not be worth it. If you are facing performance issues after doing various optimizations, then use Vue 3.
watchEffect
seems to be a simplified watch
and the main differences are
watch
can accept either a function or one or more reactive properties.watch
only runs when reactive dependencies changeI would use:
watchEffect
when I want to watch multiple reactive properties and I don't care about old valueswatch
when I want to watch one specific reactive properties and I may want old valueNote, above is what I would use them for, but may not be their only usage.
Also found in docs regarding the difference:
Compared to watchEffect, watch allows us to:
Perform the side effect lazily;
Be more specific about what state should trigger the watcher to re-run;
Access both the previous and current value of the watched state.
Source: https://composition-api.vuejs.org/api.html#watch
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With