💚 Vue.js Beginner

What are watchers in Vue?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Vue.js topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

Watchers react to data changes and execute side effects (async operations, DOM manipulation, logging) when a reactive source changes. Unlike computed properties (derive value), watchers perform actions. watch() — Composition API: watches a specific source. import { watch, ref } from "vue"; const userId = ref(1); watch(userId, async (newId, oldId) => { userData.value = await fetchUser(newId); });. Watch reactive object: watch(() => state.user.name, (newName) => { console.log(newName); });. Watch multiple sources: watch([firstName, lastName], ([newFirst, newLast]) => { ... });. Options: { immediate: true } — run immediately on mount; { deep: true } — deeply watch nested objects; { once: true } — run only once (Vue 3.4+). watchEffect() — Composition API: automatically tracks all reactive dependencies used inside the callback: watchEffect(async () => { const data = await fetch(`/api/user/${userId.value}`); });. Runs immediately, re-runs whenever userId changes. No need to specify the source. Options API watcher: watch: { searchTerm: { handler(newVal) { this.fetchResults(newVal); }, immediate: true, deep: false } }. Stopping a watcher: const stop = watch(...); stop();. Watchers created in setup() are automatically stopped when the component unmounts. watchEffect vs watch: watchEffect is simpler (auto-tracks deps, immediate); watch gives more control (old + new values, specific sources).

Pro Tip

This topic has Vue.js-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.