Why watcher is better than computed to perform asynchronous or expensive operations in response to changing data in vue.js?

Tags: , ,



Documentation of Vue.js says:

Using the watch option allows us to perform an asynchronous operation (accessing an API), limit how often we perform that operation, and set intermediary states until we get a final answer. None of that would be possible with a computed property.

While on the same page, we can see that computed property uses a function the same as watcher.

Reference: https://vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property

So my question is what is the technical reason supporting the above statement or limiting us from using computed properties instead of watchers?

Answer

It’s important to understand how computed properties work in Vue

  1. When the computed prop function (provided by you) is running, Vue is monitoring which other reactive data is accessed so it knows on what data the result depends
  2. Result of the function is cached by Vue
  3. Whenever you access the value of the computed prop (it’s getter), small chunk of Vue code is executed – it first checks whether it has value in the cache and if yes, whether some of the inputs changed from the last time the function was executed. If there is a value and no changes, function is not executed at all and cached value is returned instead

Title of your question mentions “asynchronous or expensive” …

Expensive

Expensive computation is exactly what computed props are for because the function is executed only when needed. But it is executed every time something changes, which is not always what you want. So the docs are talking about use cases when you have some stream of values – let’s say user typing – and you want perform the operation only after she stops for 200ms. Or you have some stream of data (telemetry) but want to update the graph every 2 seconds and no more.

This is not possible with computed because Vue expects function to return value every time and that value is stored in the cache for future use.

Asynchronous

As I said before, Vue expects the computed function to return a value. When you run some async call inside computed prop getter, you have no value to return (in case of asynchrony based on callbacks – but JS functions always return something) or you have a promise of the future value. So Vue takes the result of your function (undefined or promise) and store it in the cache …which is something you don’t want



Source: stackoverflow