JAVASCRIPT
Vue 3 Deep and Immediate Watchers
Master deep and immediate watchers in Vue 3's Composition API to effectively react to changes within nested reactive objects or trigger initial effects on data.
<template>
<div>
<h2>Watcher Example</h2>
<p>User Name: {{ user.name }}</p>
<p>User Age: {{ user.details.age }}</p>
<input v-model="user.name" placeholder="Edit Name" />
<input v-model.number="user.details.age" placeholder="Edit Age" type="number" />
<p>Message: {{ message }}</p>
<input v-model="message" placeholder="Edit Message" />
</div>
</template>
<script setup>
import { ref, reactive, watch } from 'vue'
const user = reactive({
name: 'Alice',
details: {
age: 30
}
})
const message = ref('Hello')
// 1. Basic Watcher for a ref
watch(message, (newValue, oldValue) => {
console.log(`Message changed from '${oldValue}' to '${newValue}'`);
});
// 2. Deep Watcher for a reactive object
// Monitors changes to any nested property within 'user'
watch(user, (newValue, oldValue) => {
console.log('User object (deep) changed:', newValue.name, newValue.details.age);
// Note: For reactive objects, newValue and oldValue are often the same proxy object.
// To compare values, you might need to deep clone or compare specific properties.
}, { deep: true });
// 3. Immediate Watcher
// Runs the callback immediately on component setup, then again on changes
watch(() => user.details.age, (newValue, oldValue) => {
console.log(`User age (immediate) is: ${newValue}. Previous: ${oldValue}`);
}, { immediate: true });
// You can combine deep and immediate:
const profile = reactive({
settings: {
theme: 'dark',
notifications: true
}
});
watch(profile, (newValue) => {
console.log('Profile settings (deep & immediate) changed:', newValue.settings);
}, { deep: true, immediate: true });
</script>
How it works: This snippet demonstrates the advanced usage of `watch` in Vue 3's Composition API, specifically focusing on `deep` and `immediate` options. A `deep` watcher is crucial for monitoring changes within nested properties of a reactive object; without it, only top-level property reassignment would trigger the watcher. An `immediate` watcher executes its callback function immediately after the component is mounted, and then again whenever the watched source changes. This is useful for initializing effects or data based on the initial value of a reactive source. The examples show how to apply these options to `ref` and `reactive` data sources.