Skip to the workspace
Pebellslearn by building
API Styles  ›  Capstone Project

Computed Properties

Computed Properties 14 mincomputed derives a value from reactive state and caches it, recalculating only when the state it reads changes.

vue / Computed Properties

Explore each scene at your own pace.

01 · The rule

The rule

Computed Properties

Shelf's header says "Finished 3 of 8" and the sidebar lists only unread books. Both are calculated from the same books array. You could write the filter directly in the template, twice, and have it rerun on every render. Or you can name the result once and let Vue remember it.

The rule

Computed derives a value, caches it, and recalculates only when its inputs change.

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

const books = ref([
  { title: 'Dune', pages: 412, read: true },
  { title: 'Circe', pages: 393, read: false },
  { title: 'Piranesi', pages: 245, read: false }
])

const unread = computed(() => books.value.filter(b => !b.read))
const finishedCount = computed(() => books.value.length - unread.value.length)
</script>

<template>
  <h2>Finished {{ finishedCount }} of {{ books.length }}</h2>
  <ul>
    <li v-for="b in unread" :key="b.title">{{ b.title }}</li>
  </ul>
</template>

What each part of the rule means:

  • Derives. You pass a getter, a function that returns a value. computed returns a read-only ref, so script code reads unread.value and the template reads unread.
  • Caches. Vue records which reactive data the getter touched, here books. Until that data changes, every read returns the stored result without running the getter again.
  • Recalculates on change. Flip a book's read flag and both computeds refresh; the header and list update.

Compare a method: function unreadList() { return books.value.filter(...) } called as {{ unreadList() }} gives the same output, but runs on every re-render of the component, even when something unrelated changed.

Rules for a good getter:

  • No side effects. Do not change other state, fetch data or touch the DOM inside it. It should only calculate. Side effects belong in watchers (Lifecycle Hooks section).
  • Depend on reactive data. computed(() => Date.now()) is computed once and never changes, because Date.now() is not reactive.
  • Treat the result as read-only. To make one writable you must supply both get and set; that is rare.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.