← Back to all snippets
JAVASCRIPT

Deep Watching Nested Reactive Data with Vue 3's watch

Learn how to effectively monitor changes in deeply nested properties of reactive objects using Vue 3's `watch` function, triggering custom logic upon data mutations.

import { reactive, watch } from 'vue';

export default {
  setup() {
    const user = reactive({
      id: 1,
      profile: {
        name: 'John Doe',
        address: {
          city: 'New York',
          zip: '10001'
        }
      },
      preferences: ['email', 'sms']
    });

    // Watch for deep changes in the entire 'user' object
    watch(user, (newValue, oldValue) => {
      console.log('User data changed deeply!');
      console.log('New Value:', JSON.stringify(newValue));
      console.log('Old Value:', JSON.stringify(oldValue));
      // Perform actions like saving to API or logging
    }, { deep: true, immediate: true });

    // Example of changing nested data
    setTimeout(() => {
      user.profile.address.zip = '10002'; // Deep change
      user.preferences.push('push_notifications'); // Array change
    }, 2000);

    return {
      user
    };
  }
};
How it works: This snippet demonstrates how to use Vue 3's `watch` function to observe changes in deeply nested properties of a reactive object. By setting the `deep: true` option in the watcher configuration, any modification within the `user` object, including its nested `profile` or `address` objects, or changes to the `preferences` array, will trigger the watcher callback. This is crucial for scenarios where you need to react to complex data structure changes, such as saving user preferences to a backend API or updating related UI components.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs