What are immediate: true and deep: true options in Vue watchers?
❓ Interview Prompt: Explain watch configuration options: immediate execution on mount and deep recursive object listening.
By default, Vue 'watch()' callbacks run lazily — only when the watched source mutates.
1. 'immediate: true':
Forces the watcher callback to execute immediately upon component creation / mounting, using the initial value of the ref. Useful for triggering an initial API fetch on component load.
2. 'deep: true':
By default, watching a reactive object only triggers if the object reference changes. Setting 'deep: true' instructs Vue to traverse all nested properties recursively, firing the callback whenever any deep property mutates. (Note: In Vue 3, watching a 'reactive()' object is automatically deep).
Code Implementation Example
import { ref, watch } from 'vue';
const userId = ref(1);
const userProfile = ref({ name: 'Alice', settings: { theme: 'dark' } });
// 1. immediate: true runs fetchUser immediately on mount
watch(userId, (newId) => {
console.log('Fetching user data for ID:', newId);
}, { immediate: true });
// 2. deep: true watches nested property changes inside userProfile
watch(userProfile, (newProfile) => {
console.log('User profile deeply updated:', newProfile);
}, { deep: true });Use immediate: true to run watchers on mount. Use deep: true to watch nested object mutations.