Computed properties

Beginner · 14 min

Deriving state with computed() in Vue 3, why results are cached by their dependencies, when to use a method instead, and writable computeds.

Before thisref and reactive

Make Apps with Danny · 14 min

Computed properties

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Make Apps with DannyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `computed(() => expr)` declares a value derived from other reactive state. Vue tracks every reactive value the getter reads and re-runs it only when one of them changes.
  • The result is cached: reading a computed ten times in one render runs the getter once. A method called from the template runs on every render, whether or not its inputs changed.
  • A computed is lazy. If nothing reads it, its getter does not run at all, even when its dependencies change.
  • Getters should be pure: no API calls, no mutation of other state, no DOM work. Side effects belong in a watcher, and the computed's own value should be treated as read-only.
  • Since Vue 3.4, a computed only notifies whatever depends on it when its returned value actually changes, so returning a fresh object or array every time throws that saving away.
  • Passing `{ get, set }` creates a writable computed, useful for exposing a derived value to `v-model` while writing changes back to the real source.

Logic that keeps leaking into the template

Say a component holds a list of tasks and wants to show how many are still open:

<template>
  <p>{{ tasks.filter(t => !t.done).length }} open</p>
  <p v-if="tasks.filter(t => !t.done).length === 0">All done</p>
</template>

It works, but the filter is written twice, runs twice per render, and the template is now holding business logic. You could move it into a function and call openCount() from both places. That fixes the duplication but not the waste. The function still runs every time the template renders, including re-renders triggered by state that has nothing to do with tasks.

What you want is a value that is defined in terms of other state, kept up to date automatically, and only recalculated when its inputs actually change. That is a computed property.

computed(): a derived ref

<script setup>
import { ref, computed } from 'vue'

const tasks = ref([
  { id: 1, title: 'Write lesson', done: true },
  { id: 2, title: 'Record video', done: false },
])

const openCount = computed(() => tasks.value.filter(t => !t.done).length)
</script>

<template>
  <p>{{ openCount }} open</p>
  <p v-if="openCount === 0">All done</p>
</template>

computed() takes a getter function and returns a read-only ref. In script you read it as openCount.value; in the template it is unwrapped like any other top-level ref.

The first time something reads openCount, Vue runs the getter and records every reactive value it touched along the way: here tasks.value and the done property of each task. The result is stored. Every later read returns the stored result without running the getter. When one of the recorded dependencies changes (a task is added or a done flag flips), Vue marks the computed as stale. The getter runs again only the next time someone reads it.

Think of it as a spreadsheet formula cell. =COUNTIF(B:B, FALSE) does not recount on every glance; it recounts when column B changes.

Computed versus a method

The difference shows up as soon as a component re-renders for an unrelated reason:

<script setup>
import { ref, computed } from 'vue'

const query = ref('')
const products = ref([/* 5,000 items */])

const visible = computed(() =>
  products.value.filter(p => p.name.toLowerCase().includes(query.value.toLowerCase()))
)

function visibleViaMethod() {
  return products.value.filter(p => p.name.toLowerCase().includes(query.value.toLowerCase()))
}

const menuOpen = ref(false)
</script>

Toggling menuOpen re-renders the component. visible returns its cached array instantly because neither products nor query changed. visibleViaMethod() filters all 5,000 products again. A method is the right tool when you genuinely want a fresh result each time, or when you need to pass arguments. A computed is the right tool for “this value, derived from that state.”

Two consequences of how dependencies are tracked are worth knowing:

  • Only reactive reads count. computed(() => Date.now()) never updates, because Date.now() is not reactive state. The getter has nothing to depend on.
  • It is lazy. If no template, watcher, or other computed reads visible, its getter never runs, even while query changes.

Keep the getter pure

A computed getter should do one thing: read state and return a value. No fetch, no writes to other refs, no DOM manipulation. Vue may run it at different times than you expect, or skip running it entirely when nobody reads it, so side effects inside it are unreliable.

A classic accidental side effect is in-place array methods:

// Bug: sort() mutates tasks.value, the computed's own dependency
const byTitle = computed(() => tasks.value.sort((a, b) => a.title.localeCompare(b.title)))

// Fine: sort a copy
const byTitle = computed(() => tasks.value.toSorted((a, b) => a.title.localeCompare(b.title)))

Treat the returned value as read-only too. If you need to react to a change by doing something, such as saving to localStorage or calling an API, that is a job for a watcher.

Computed stability (Vue 3.4+)

Since Vue 3.4, when a computed re-runs, it compares the new result with the old one. If they are the same (by Object.is), it does not notify anything that depends on it. A computed like const isEven = computed(() => count.value % 2 === 0) will not trigger re-renders when count goes from 2 to 4, because the result stayed true.

That saving disappears if the getter returns a new object or array every time, since a fresh object is never identical to the last one. If that matters, return primitives where you can. Vue 3.4 also passes the previous value to the getter, so you can hand back the old object when nothing meaningful changed:

const summary = computed((previous) => {
  const next = { open: openCount.value, total: tasks.value.length }
  if (previous && previous.open === next.open && previous.total === next.total) {
    return previous
  }
  return next
})

This is an optimisation, not something to reach for by default. Most computeds return cheap values and never need it.

Writable computeds

Occasionally you want to write to a derived value. Pass an object with get and set:

<script setup>
import { ref, computed } from 'vue'

const firstName = ref('Ada')
const lastName = ref('Lovelace')

const fullName = computed({
  get: () => `${firstName.value} ${lastName.value}`,
  set: (value) => {
    const [first, ...rest] = value.split(' ')
    firstName.value = first
    lastName.value = rest.join(' ')
  },
})
</script>

<template>
  <input v-model="fullName" />
</template>

The setter does not store anything itself. It translates the write into updates to the real state, and the getter then recomputes from that state. The same pattern is a common way to wire v-model through a component, covered in v-model on components.

What the video covers

Danny’s episode builds the same derived value first as a method and then as a computed() with the Composition API, which makes the caching difference concrete. The computed section starts at 4:12. The last few minutes introduce watch, which is the next lesson. The video does not cover computed stability, the previous-value argument, or writable computeds, so those are carried above.

LearnVue’s two short videos in the “go deeper” links pick up where it stops. One, based on a post by Vue core team member Thorsten Lünborg, covers cases where a computed’s laziness and caching do not help. It predates 3.4, which softened some of that advice. The other explains computed stability and why returning fresh objects defeats it. If you know React, a computed is roughly useMemo with the dependency array worked out for you. Compare with useMemo and useCallback.

Where this fits

Computeds derive values. When a change should cause something to happen outside the component’s state, you need watchers.

Check yourself

  1. 01A template calls `{{ formatTotal() }}` three times, and `formatTotal` is a method that sums a cart. How does that differ from three reads of a `const total = computed(...)`?

    The method is a plain function, so the template runs it three times per render, and again on every re-render for any reason, even an unrelated piece of state changing. The computed runs its getter once, caches the result, and returns the cached value to all three reads. It only re-runs after one of the reactive values it read, such as the cart items, changes.

  2. 02Why does `const now = computed(() => Date.now())` never update?

    A computed re-evaluates only when a reactive dependency it read changes. `Date.now()` is not reactive, so the getter has no dependencies at all and Vue never has a reason to run it again. To show a ticking clock, store the time in a ref and update it from a timer, then derive from that ref.

  3. 03What is wrong with `const sorted = computed(() => items.value.sort((a, b) => a.price - b.price))`?

    `Array.prototype.sort` sorts in place, so the getter mutates `items`, which is a side effect on its own dependency. Copy first, with `[...items.value].sort(...)` or `items.value.toSorted(...)`, so the getter only reads its inputs and returns a new value.

  4. 04When would you write a computed with both `get` and `set`?

    When something needs to write to a derived value and you want the write to update the underlying source. A common case is binding `v-model` to a value that is stored differently, such as a full name split into first and last fields, or a prop whose changes must be emitted to the parent. The getter derives the value; the setter translates a write back into updates of the real state.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark