Vue3 Fundamentals · Reactivity

Stop a watcher

watch control

Stop a watcher

A watcher keeps running for the life of the component. Sometimes you want to end it early — once a value has settled, or when the user leaves a screen. watch returns a handle with a stop method:

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

const count = ref(0);
const log = ref([]);

const stop = watch(count, (value) => {
  log.value.push(value);
});
</script>

<template>
  <button @click="count++">Count: {{ count }}</button>
  <button @click="stop">Stop</button>
  <p>{{ log.join(', ') }}</p>
</template>

Calling stop() ends the watcher: later changes to count no longer run the callback, so the log stops growing. The handle also offers pause() and resume() to silence a watcher temporarily, and watch accepts { once: true } to stop itself after the first change.

The Test for this Lesson mounts your component, clicks the count button twice, clicks Stop, then clicks the count button again, and checks the log. Your component is exported from App.vue.

Challenge

The log keeps growing after you press Stop. Keep the watcher's handle and stop it on demand: export an App component from App.vue with a Count button, a Stop button, and a paragraph listing the logged values joined with , .

The Test clicks the count button twice, clicks Stop, then clicks the count button again, and expects the paragraph to read 1, 2. The starter never stops the watcher, so the log reads 1, 2, 3 and the Test fails.

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

const count = ref(0);
const log = ref([]);

watch(count, (value) => {
  log.value.push(value);
});
</script>

<template>
  <button @click="count++">Count: {{ count }}</button>
  <button>Stop</button>
  <p>{{ log.join(', ') }}</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.