Watchers let you react to changes in data and run code when something changes. They help you do extra work outside the main display, like fetching data or logging.
0
0
Watchers for side effects in Vue
Introduction
You want to fetch new data when a user changes a search term.
You need to save form data automatically when a user edits it.
You want to run a function when a specific value changes, like toggling a setting.
You want to log or track changes in a variable for debugging.
You want to trigger animations or side effects when data updates.
Syntax
Vue
watch(source, callback, options?) // source: a reactive reference or getter function // callback: function(newValue, oldValue) to run on change // options: optional object like { immediate: true }
The source can be a reactive variable or a function returning a value.
The callback runs every time the source changes, receiving new and old values.
Examples
Watch a simple reactive variable and log changes.
Vue
import { ref, watch } from 'vue' const count = ref(0) watch(count, (newVal, oldVal) => { console.log(`Count changed from ${oldVal} to ${newVal}`) })
Watch a computed value (like a prop) and fetch data when it changes.
Vue
watch(() => props.userId, (newId, oldId) => {
fetchUserData(newId)
})Run the watcher immediately on setup and whenever
searchTerm changes.Vue
watch(searchTerm, async (newTerm) => { results.value = await fetchResults(newTerm) }, { immediate: true })
Sample Program
This Vue component watches the name input. When the user types a new name, the watcher updates the greeting message automatically.
Vue
<script setup> import { ref, watch } from 'vue' const name = ref('Alice') const greeting = ref('') watch(name, (newName) => { greeting.value = `Hello, ${newName}!` }) </script> <template> <input v-model="name" aria-label="Name input" /> <p>{{ greeting }}</p> </template>
OutputSuccess
Important Notes
Watchers are good for side effects but avoid heavy logic inside them.
Use immediate: true if you want the watcher to run once right away.
Remember to clean up watchers if you create them manually to avoid memory leaks.
Summary
Watchers run code when reactive data changes.
They are useful for side effects like fetching or logging.
Use watch with a source and a callback function.