Vue 3·Vue from reactivity to a routed app

Computed and watch

Derive values with computed and run side effects with watch.

Intermediate 13 min read Lesson 3 of 300 Challenge included
What you will be able to do
  • Use computed for derived values.
  • Use watch for side effects, not for data transformation.
  • Use watchEffect when you want automatic dependency tracking.
  • Keep computed functions pure.

In plain English

A computed property is a cached derivation: it recalculates only when its dependencies change. watch is for side effects such as saving to storage or fetching when a filter changes. Do not use watch to derive state that should be computed.

filter.vueJavaScript
<script setup>
import { computed, ref, watch } from 'vue'

const query = ref('')
const lessons = ref(['HTML', 'CSS', 'JavaScript'])
const filtered = computed(() =>
  lessons.value.filter((lesson) => lesson.toLowerCase().includes(query.value.toLowerCase())),
)

watch(query, (value) => localStorage.setItem('filter', value))
</script>

<template>
  <input v-model="query" placeholder="Filter">
  <ul><li v-for="lesson in filtered" :key="lesson">{{ lesson }}</li></ul>
</template>
Your turn

Derive a total

Easy

Given a ref array of minute values, create a computed total.

JAVASCRIPT · starter
const minutes = ref([12, 18, 9])
Check your understanding before moving on.
Knowledge checkQuestion 1

When does a computed property recalculate?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Events and forms
Lesson 3 of 300 · 0% of course