Blog>
Snippets

Watching Deep Object Changes

Use Vue's watchEffect to deeply watch a reactive object for any nested changes and react accordingly.
const { reactive, watchEffect } = Vue;

// Define a reactive object
const state = reactive({
    user: {
        name: 'Alice',
        age: 30,
        address: {
            street: '123 Vue Street',
            city: 'Vueville',
        }
    }
});

// Watch for changes deeply
watchEffect(() => {
    // This effect runs initially and whenever any nested property of 'state' changes
    console.log('Detected a change in the state object:', JSON.stringify(state));
}, { deep: true });

// Triggering a change in a nested object
state.user.address.city = 'Vuexopolis'; // The watchEffect callback will log the updated state
This code defines a reactive object called 'state' with nested properties. It uses Vue's watchEffect with the 'deep' option to observe deep changes within the object. The watchEffect is used to log the entire state to the console whenever any property within 'state' changes, demonstrating a deep watch. An example change is made to the nested city property to trigger the effect.