Understanding the inner workings of computed
properties in Vue is crucial. Typically, developers provide Vue with a getter function that dictates how the computed property's value is calculated.
- During the execution of the
computed
prop getter (the function you supply), Vue monitors which other reactive data
is accessed to determine the dependencies of the result.
- The result of the getter is cached by Vue for efficiency.
- Upon accessing the value of the
computed
prop, Vue runs a small piece of code - it checks if the value is in the cache and if any input data has changed since the last execution of the getter. If the value exists and there are no changes, the getter is not re-executed; instead, the cached value is returned.
Your question title mentions "asynchronous or expensive"...
Expensive
Expensive computations are precisely what computed
props excel at because the getter is only executed when necessary. However, it's run every time something changes, which may not always be desired. The documentation discusses scenarios where continuous values, like user input or telemetry data, need processing only after specific conditions are met (e.g., 200ms delay or every 2 seconds).
This behavior is not achievable with computed
as Vue expects the getter to return a value on every call, storing it in the cache for future use.
Asynchronous
Vue mandates that the computed
getter should return a value. When an asynchronous operation is performed within the computed
prop getter, there's either nothing immediate to return (in callback-based asynchrony) or a promise for a future value. In such cases, Vue caches the result (undefined or promise), which is often undesirable. For tasks involving asynchrony, using watch
is typically a better choice.