Track dependencies with watchEffect
With watch you name the source. Often you do not want to: you want to run some
code and have Vue figure out what it depends on. watchEffect runs a function
immediately, tracks every reactive value it reads, and re-runs when any of them
changes.
<script setup>
import { ref, watchEffect } from 'vue';
const count = ref(0);
const message = ref('');
watchEffect(() => {
message.value = `count is ${count.value}`;
});
</script>
<template>
<button @click="count++">Count: {{ count }}</button>
<p>{{ message }}</p>
</template>
The effect reads count.value, so Vue records count as a dependency. When the
count changes, the effect runs again and rewrites message. You never listed
count — reading it was enough.
The effect also runs once on setup, so message is filled before the first
render. That is the difference from watch: watch waits for a change, while
watchEffect runs now and re-runs on every dependency change. Use it when the
whole body should re-run and you do not need the previous value.
The Test for this Lesson mounts your component, clicks the button once, and
checks the message. Your component is exported from App.vue.
Challenge
The button counts, but the message never follows. Use watchEffect so the
message tracks the count: export an App component from App.vue that
renders a button labelled Count: 0 and a paragraph reading count is 0,
updated on each click.
The Test mounts your component, clicks the button once, and expects the paragraph
to read count is 1. The starter never runs an effect, so the paragraph stays
empty and the Test fails.