React to changes with watch
A computed derives a value. Sometimes you need to do something when a value changes — log it, save it, start a request. That work is a side effect, and it does not belong in a computed.
watch takes a reactive source and a callback. Vue calls the callback whenever
the source changes, passing the new value and the previous one:
<script setup>
import { ref, watch } from 'vue';
const count = ref(0);
const changes = ref([]);
watch(count, (next, prev) => {
changes.value.push(`${prev} → ${next}`);
});
</script>
<template>
<button @click="count++">Count: {{ count }}</button>
<p>{{ changes.join(', ') }}</p>
</template>
The source here is the count ref itself, so watch fires on every change. The
callback receives the new value first and the old value second, which is why the
paragraph records each step, not only the latest value.
watch is lazy: it does not run on setup, only after the source changes. Reach
for it when you need the previous value or want to react to one specific source.
The Test for this Lesson mounts your component, clicks the button twice, and
checks the recorded changes. Your component is exported from App.vue.
Challenge
The button counts, but nothing records the changes. Add a watch so each step is
logged: export an App component from App.vue that renders a button
labelled Count: 0 and a paragraph listing every change as old → new, joined
with , .
The Test mounts your component, clicks the button twice, and expects the
paragraph to read 0 → 1, 1 → 2. The starter never watches the count, so the
paragraph stays empty and the Test fails.