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://v2.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
?
Advertisement
Answer
It’s important to understand how computed
properties work in Vue. In most cases what developer gives to Vue is a getter which is a function, which defines how the value of computed property is computed.
- When the
computed
prop getter (function provided by you) is running, Vue is monitoring which other reactivedata
is accessed so it knows on what data the result depends - Result of the getter is cached by Vue
- Whenever you access the value of the
computed
prop, 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 getter was executed. If there is a value and no changes, the getter 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 getter 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 only every 2 seconds
This is not possible with computed
because Vue expects getter 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
getter 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. So if there is any asynchrony involved, watch
is always better…