Skip to the workspace
Pebellslearn by building
Lifecycle Hooks  ›  Capstone Project

Watchers

Watchers 14 minwatch runs a callback when a reactive source changes, the right tool for side effects like saving or fetching.

vue / Watchers

Explore each scene at your own pace.

01 · The rule

The rule

Watchers

Shelf forgets everything on refresh. You want the books saved to the browser's storage every time the list changes, and a book's cover fetched whenever the selected book changes. Neither is a value to display, so computed is the wrong tool. These are side effects triggered by a change: the job of watch.

The rule

Computed returns a value; watch does something when a value changes.

watch takes a source and a callback. When the source changes, the callback runs with the new and old values:

import { ref, watch } from 'vue'

const selectedId = ref(1)
const cover = ref(null)

watch(selectedId, async (newId, oldId) => {
  const res = await fetch(`/api/books/${newId}/cover`)
  cover.value = await res.json()
})

What can be a source:

  • A ref: watch(selectedId, ...).
  • A getter function: watch(() => filters.genre, ...). You need this for a property of a reactive object. watch(filters.genre, ...) passes a plain string, which cannot be watched.
  • A reactive object: watch(filters, ...) watches it deeply, every nested property.
  • An array of these, to react to any of several sources.

Options go in a third argument:

  • deep: true reacts to changes inside nested objects or arrays. Watching a ref that holds an array fires only when .value is replaced; add deep to catch a push or a flipped flag inside a book.
  • immediate: true runs the callback once right away, not just on the first change.
watch(books, (list) => {
  localStorage.setItem('shelf', JSON.stringify(list))
}, { deep: true, immediate: true })

watchEffect is the automatic version: you give it one function, it runs immediately, and it re-runs whenever any reactive value it read changes. No source to list, but also no old value.

watchEffect(() => {
  document.title = `Shelf (${books.value.length})`
})
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.