Watchers let you run side effects (API calls, logging, DOM manipulation) in response to reactive state changes.
import { ref, watch } from 'vue'
const query = ref('')
// Watch a single ref
watch(query, (newVal, oldVal) => {
console.log(`Query changed from "${oldVal}" to "${newVal}"`)
fetchResults(newVal)
})
// Watch with options
watch(query, fetchResults, {
immediate: true, // run immediately on mount
deep: true, // deep watch for nested objects
})
// Watch multiple sources
const page = ref(1)
const perPage = ref(10)
watch([query, page, perPage], ([q, p, pp]) => {
fetchResults(q, p, pp)
})
import { ref, watchEffect } from 'vue'
const userId = ref(1)
// Runs immediately; tracks any reactive values accessed inside
watchEffect(async () => {
const data = await fetchUser(userId.value) // tracked automatically
user.value = data
})
const stop = watch(query, fetchResults)
// Later:
stop() // unregister the watcher