Every watcher returns a function to stop it.
1<template>
2 <div>
3 <p>Count: {{ count }}</p>
4 <button @click="count++">Increment</button>
5 <button @click="stopWatching">Stop watcher</button>
6 </div>
7</template>
8
9<script setup>
10import { ref, watchEffect } from 'vue'
11
12const count = ref(0)
13
14// watchEffect returns a stop function
15const stop = watchEffect(() => {
16 console.log('Count:', count.value)
17})
18
19function stopWatching() {
20 stop() // Stop the watcher
21 console.log('Watcher stopped')
22}
23</script>1<script setup>
2import { ref, watch } from 'vue'
3
4const data = ref(null)
5const isLoading = ref(true)
6
7// Watcher with stop condition
8const stopWatch = watch(data, (newData) => {
9 if (newData && newData.complete) {
10 console.log('Data complete, stopping watcher')
11 stopWatch()
12 }
13})
14</script>1<script setup>
2import { ref, watch, onMounted, onUnmounted } from 'vue'
3
4const count = ref(0)
5let stopWatch
6
7onMounted(() => {
8 // Start watcher after mounting
9 stopWatch = watch(count, (val) => {
10 console.log('Count:', val)
11 })
12})
13
14onUnmounted(() => {
15 // Stop on unmount
16 if (stopWatch) {
17 stopWatch()
18 }
19})
20</script>1import { ref, watch } from 'vue'
2
3const count = ref(0)
4
5const { stop, pause, resume } = watch(count, (val) => {
6 console.log('Count:', val)
7})
8
9// Pause temporarily
10pause()
11
12// Resume
13resume()
14
15// Stop permanently
16stop()