We use cookies to enhance your experience on the site
CodeWorlds

Stopping Watchers

Every watcher returns a function to stop it.

Stop Watch

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>

Conditional Watcher

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>

Watcher in Lifecycle

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>

Pausing and Resuming (Vue 3.5+)

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()
Go to CodeWorlds