Lesson 5 / 25

Computed Properties

Cached values derived from state.

Derived state with caching

computed(() => ...) creates a read-only ref whose value is derived from other reactive state. It is cached: the getter re-runs only when one of its reactive dependencies changes, unlike a method called in the template, which runs on every render. Keep getters free of side effects (no API calls or DOM changes) and do not mutate the computed result. For rare cases you can create a writable computed by passing an object with get and set.

Filtering and a writable computed

Derived values instead of duplicated state.

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

const items = ref([
  { name: 'Keyboard', price: 40, inStock: true },
  { name: 'Monitor', price: 180, inStock: false },
])
const firstName = ref('Asha')
const lastName = ref('Verma')

const available = computed(() => items.value.filter(i => i.inStock))
const total = computed(() => available.value.reduce((s, i) => s + i.price, 0))

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

<template>
  <p>{{ available.length }} items available, total {{ total }}</p>
  <input v-model="fullName" />
</template>

Derive, do not duplicate

If a value can be calculated from existing state, make it computed instead of storing it separately and keeping two copies in sync by hand.

Quick check: When does a computed getter re-run?

  • On every component render
  • Only when one of its reactive dependencies changes
  • Every second on a timer
  • Only when called with new arguments
Answer

Only when one of its reactive dependencies changes — Computed values are cached.