Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 87 ยท Reactivity Fundamentals

Computed Properties

Learn how Vue computed properties work - caching versus methods, read-only getters, writable computed, why getters must stay free of side effects, and the previous-value argument.

Most of the data on a screen is not stored; it is derived. A cart total comes from prices and quantities, a "3 items left" label comes from a list, a full name comes from a first and a last name. You could recalculate these values by hand every time something changes, but that is exactly the kind of bookkeeping that creates stale-value bugs.

A computed property is Vue's tool for derived state. You describe how the value is calculated from other reactive values, and Vue keeps it up to date and caches the result. If you have not met reactive state yet, read Reactive State with ref and reactive Objects first; this lesson builds directly on them.

Your first computed

computed() takes a getter function and returns a computed ref. Inside setup() you read it with .value, just like any ref; in a template Vue unwraps it for you.

JavaScript
import { ref, computed } from "vue";

const price = ref(4);
const quantity = ref(3);
const total = computed(() => price.value * quantity.value);

console.log(total.value); // 12
quantity.value = 5;
console.log(total.value); // 20

While the getter runs, Vue records every reactive value it reads (price and quantity here). Those become the computed's dependencies. When one of them changes, the computed is marked stale, and anything that depends on it (a template, a watcher, another computed) is told to update.

A computed is read-only by default. Assigning to total.value does nothing except print a warning in development builds. A computed describes a relationship; it does not own any data.

Computed versus a method

You can get the same text on screen with a method call in the template: {{ calculateTotal() }}. The output looks identical, so why bother with computed? The answer is caching.

  • A computed runs its getter only when it is read and one of its dependencies has changed since the last run. Otherwise it returns the stored result.
  • A method runs every single time it is called, once per call site, on every re-render of the component.

For a cheap expression the difference is invisible. For filtering and sorting a thousand rows, or for a value used in several places, it matters. Try it below. The counters show how many times each version actually ran.

Computed caches, methods do not

On the first render the computed ran once and the method twice (one run per use). Press Unrelated click: the component re-renders, the method runs two more times, and the computed does not run at all because price and quantity did not change. Press Quantity +1 and the computed runs once, because the new value is shared by both places that read it.

(The counters live in a plain object on purpose. Writing to a ref inside a getter would be a side effect, which is the subject of a later section.)

flowchart LR
    S["A source ref changes"] --> D["Computed marked stale"]
    D --> R{"Is .value read?"}
    R -->|"not yet"| W["Nothing runs"]
    R -->|"yes"| C["Getter runs, result is cached"]
    C --> K["Later reads return the cache until a source changes"]

A computed is lazy: it does no work until someone reads it, and it reuses its result until a dependency changes.

Two practical consequences follow from this model:

  • Non-reactive inputs are not tracked. computed(() => Date.now()) never updates, because Date.now() is not a reactive value. The getter ran once and its dependency list is empty, so the cache is valid forever.
  • Unchanged results stop the chain. Since Vue 3.4, if a computed recalculates and produces the same value as before (compared with Object.is), the things that depend on it are not notified. A computed such as isAdult = computed(() => age.value >= 18) does not re-render its component while age moves from 30 to 31.

Computed from collections

Computed properties shine when they derive from lists. The getter below filters and counts in one pass of thinking, and every part of the template that needs the result simply reads it.

JavaScript
const todos = ref([
  { text: "Write lesson", done: true },
  { text: "Review lesson", done: false },
]);

const remaining = computed(() => todos.value.filter((t) => !t.done));
const summary = computed(() => `${remaining.value.length} of ${todos.value.length} left`);

Computeds can depend on other computeds (summary reads remaining). Vue sorts out the order. Prefer several small computeds with clear names over one large getter; each one is easy to read and cached on its own.

One more rule of thumb: if you sort inside a getter, sort a copy. todos.value.sort(...) mutates the source array in place, which is a side effect. Write [...todos.value].sort(...) or todos.value.toSorted(...) instead.

Writable computed

Sometimes it helps to treat a derived value as if it were a normal variable that can also be assigned. Pass an object with get and set to computed(). The setter does not store anything in the computed; it updates the sources, and the getter then produces the new value.

Writable computed and the previous value

Editing the input calls the setter, which splits the text and updates first and last; the getter then rebuilds the same name. Pressing the button shows how a multi-word last name survives: "Brewster Hopper" lands in last.

Use writable computeds sparingly. They are handy for adapting a value for an input (see Two-Way Binding with v-model), but a computed with a surprising setter can hide where state really lives.

The previous value

Since Vue 3.4 the getter receives one argument: the value it returned the last time it ran (undefined on the first run). That makes a few things easy without extra state, such as a running maximum:

JavaScript
const highest = computed((previous) => Math.max(previous ?? score.value, score.value));

In the example above, raising the score to 15 and lowering it to 12 leaves highest at 15. There is one catch: the argument is the previous computed result, and a computed only runs when it is read. If the score changes twice and nothing reads highest in between, the intermediate value is never seen. Do not use the previous value for anything that must observe every change; use a watcher for that.

Keep getters pure

A getter should do one thing: calculate and return a value from its inputs. Avoid:

  • Changing other state (count.value++, pushing to an array). The result depends on how often the getter happens to run, which you do not control.
  • Asynchronous work such as fetch. A getter must return its value synchronously; a promise would just be the cached value.
  • DOM access or timers. These belong in lifecycle hooks or watchers.

The rule is simple: when you want to compute a value, use computed; when you want to react to a change by doing something, use watch. A computed also never runs code you want exactly once per change, because Vue may skip it (nobody reads it) or share it (several readers).

If a getter is hard to name as "the thing that equals ...", it is probably a watcher in disguise.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A component re-renders because an unrelated ref changed. What happens to a computed whose dependencies did not change?

    A computed re-runs its getter only when one of the reactive values it read has changed. Otherwise the cached result is reused, which is the main difference from a method call in the template.
  2. 2. What does this computed return the second time you read it? const now = computed(() => Date.now())

    Vue only tracks reactive values. The getter reads none, so it has no dependencies and its first result stays cached.
  3. 3. In a writable computed, what should the set function do?

    A computed owns no data. The setter translates the assigned value into changes to the sources (for example first and last name), and the getter derives the result from them.
  4. 4. Which of these does NOT belong inside a computed getter?

    Fetching and mutating other state are side effects. Getters should be pure and synchronous. Use a watcher or a lifecycle hook for side effects.

Summary

  • computed(() => ...) derives a value from reactive sources and returns a ref; read it with .value in scripts, plainly in templates.
  • The result is cached and the getter is lazy: it re-runs only when read after a dependency changed.
  • A method call in the template runs on every render and for every use; a computed runs once per change.
  • Only reactive reads are tracked, so Date.now() or plain variables do not refresh a computed.
  • Pass { get, set } for a writable computed; the setter updates the sources.
  • The getter's first argument is the previous result (Vue 3.4+), but a computed only sees values when it is read.
  • Keep getters pure: no mutation, no async work, no DOM. Use watchers for side effects.

Next, learn how to run code in response to changes in Watchers.