Computed Properties

Derived State — Cached & Reactive

Computed Properties

A computed is a ref-like value derived from other reactive sources. It caches its result and re-runs only when inputs change.

4 min read Level 2/5 #vue#computed
What you'll learn
  • Define a read-only computed
  • Define a writable computed with get/set
  • Compare to a regular function

A computed is a reactive value derived from other reactive sources. It looks like a ref (you read .value), but Vue caches it and only re-runs the getter when its dependencies change.

Read-Only Computed

import { ref, computed } from 'vue'

const first = ref('Ada')
const last = ref('Lovelace')
const full = computed(() => `${first.value} ${last.value}`)

console.log(full.value) // 'Ada Lovelace'
<template>
  <p>Hello, {{ full }}!</p>
</template>

Writable Computed

Pass an object with get and set to allow assignment.

const full = computed({
  get: () => `${first.value} ${last.value}`,
  set: (val: string) => {
    const [f, l] = val.split(' ')
    first.value = f
    last.value = l
  },
})

full.value = 'Grace Hopper' // updates first and last

Computed vs Function

A function in a template re-runs on every render. A computed re-runs only when its reactive inputs change — better for expensive work.

<template>
  <!-- runs every render -->
  <p>{{ expensiveCalc() }}</p>
  <!-- runs only when inputs change -->
  <p>{{ expensive }}</p>
</template>

<script setup>
import { computed } from 'vue'
const expensive = computed(() => /* heavy work */ 0)
</script>
Watchers — watch() & watchEffect() →