Vue3 Fundamentals · Reactivity

Derive state with computed

computed

Derive state with computed

Some values are not stored — they are worked out from other state. A total, a full name, a filtered list. If you compute them by hand in the template, the work repeats on every render, and the same expression gets copied around.

computed wraps an expression and caches its result. Vue tracks the reactive values the expression reads and recomputes only when one of them changes:

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

const count = ref(0);
const doubled = computed(() => count.value * 2);
</script>

<template>
  <button @click="count++">Count: {{ count }}</button>
  <p>Double: {{ doubled }}</p>
</template>

Inside the function you read count.value; in the template doubled is unwrapped like a ref, so {{ doubled }} shows the number. Because doubled depends on count, changing the count updates both.

Use computed for values derived from state, and ref for values you set directly. A computed is read-only by default: you do not assign to it, you change the state it reads.

The Test for this Lesson mounts your component, clicks the button once, and checks the derived label. Your component is exported from App.vue.

Challenge

The button works, but the Double label is stuck. Derive it with computed so it follows the count: export an App component from App.vue that renders a button labelled Count: 0 and a paragraph labelled Double: 0, doubling the count on each click.

The Test mounts your component, clicks the button once, and expects the paragraph to read Double: 2. The starter computes the double once, so it never updates and the Test fails.

App.vue
<script setup>
import { ref } from 'vue';

const count = ref(0);
const doubled = count.value * 2;
</script>

<template>
  <button @click="count++">Count: {{ count }}</button>
  <p>Double: {{ doubled }}</p>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.