Vue 10: Watchers
easy⏱ 5 mincoursevue
watch vs. computed
computed derives and returns a value synchronously, meant to be read in the template. watch doesn't return anything — it exists purely to run side effects (logging, timers, API calls, syncing to localStorage) in reaction to a change. Reach for computed when you need a value; reach for watch when you need to do something.
// computed: derives a value, no side effects
const fullName = computed(() => first.value + ' ' + last.value);
// watch: reacts to a change with a side effect
watch(first, (newVal, oldVal) => {
console.log('first changed from', oldVal, 'to', newVal);
});
Debouncing with watch
Each time the watched source changes, clear the previous setTimeout before scheduling a new one — that way, only the last change within the delay window actually triggers the expensive work, instead of running it on every keystroke.
let timer = null;
watch(query, (newQuery) => {
clearTimeout(timer);
timer = setTimeout(() => {
runExpensiveSearch(newQuery);
}, 400);
});
Build the debounced search box
Create a query ref bound with v-model, and a watch(query, ...) that debounces with setTimeout/clearTimeout before filtering a list of packages. Add a computed resultCount to show how many matched.