JAVASCRIPT
Using Deep and Immediate Watchers in Vue 3
Master Vue 3 watchers by leveraging `deep` and `immediate` options to observe changes in nested object properties and execute callbacks on initial component render.
<script setup>
import { ref, watch } from 'vue';
const user = ref({
name: 'Alice',
details: {
age: 30,
city: 'New York'
}
});
const message = ref('');
// Watch a reactive object deeply for any nested changes
watch(user, (newValue, oldValue) => {
message.value = `User object changed! New city: ${newValue.details.city}`;
console.log('User object changed (deep watch):', newValue, oldValue);
}, { deep: true, immediate: true }); // immediate: runs handler on initial render
// Example of changing a nested property
setTimeout(() => {
user.value.details.city = 'Los Angeles';
user.value.name = 'Alicia'; // Also triggers, as deep is true
}, 2000);
// Another example: watching a specific property with deep
const settings = ref({
theme: 'dark',
preferences: {
notifications: true,
language: 'en'
}
});
watch(() => settings.value.preferences, (newPrefs, oldPrefs) => {
console.log('Preferences changed (deep, non-immediate):', newPrefs, oldPrefs);
}, { deep: true });
setTimeout(() => {
settings.value.preferences.notifications = false;
}, 4000);
</script>
<template>
<div>
<p>User Name: {{ user.name }}</p>
<p>User City: {{ user.details.city }}</p>
<p>Watch Message: {{ message }}</p>
<p>Notifications: {{ settings.preferences.notifications }}</p>
</div>
</template>
How it works: This snippet illustrates how to use Vue 3's `watch` function with the `deep` and `immediate` options. The `deep: true` option ensures that the watcher triggers even when nested properties of a reactive object change, not just when the object reference itself changes. The `immediate: true` option executes the watch callback immediately upon the component's setup, allowing you to run initial logic based on the watched source without waiting for the first change. This provides fine-grained control over reacting to data mutations.