← Back to all snippets
JAVASCRIPT

Watching Deeply Nested Reactive Objects in Vue 3

Learn to effectively monitor changes within deeply nested properties of a reactive object using Vue 3's `watch` function with the `deep` option, essential for complex state management.

// App.vue
<template>
  <div>
    <h2>User Profile Editor</h2>
    <p>Name: {{ user.name }}</p>
    <p>Email: {{ user.contact.email }}</p>
    <p>City: {{ user.address.city }}</p>

    <input v-model="user.name" placeholder="Edit Name" /><br/>
    <input v-model="user.contact.email" placeholder="Edit Email" /><br/>
    <input v-model="user.address.city" placeholder="Edit City" /><br/>

    <p style="margin-top: 20px;">Logs:</p>
    <div v-for="(log, index) in changeLogs" :key="index">{{ log }}</div>
  </div>
</template>

<script setup>
import { reactive, watch, ref } from 'vue';

const user = reactive({
  name: 'John Doe',
  age: 30,
  contact: {
    email: '[email protected]',
    phone: '123-456-7890'
  },
  address: {
    street: '123 Main St',
    city: 'Anytown',
    zip: '12345'
  }
});

const changeLogs = ref([]);

// Watch the entire 'user' object deeply
watch(user, (newValue, oldValue) => {
  // For demonstration, we just log that something changed.
  // In a real app, you might compare specific properties.
  changeLogs.value.push(`User object changed at ${new Date().toLocaleTimeString()}.`);
  // console.log('Old Value:', oldValue); // oldValue is a deep copy
  // console.log('New Value:', newValue);
}, { deep: true });

// Example of watching a specific nested property (without deep needed for this specific path)
// watch(() => user.contact.email, (newEmail, oldEmail) => {
//   changeLogs.value.push(`Email changed from ${oldEmail} to ${newEmail}`);
// });
</script>
How it works: This snippet demonstrates how to use Vue 3's `watch` function with the `deep: true` option to monitor changes within a reactive object, including its nested properties. When `user.name`, `user.contact.email`, or `user.address.city` is modified, the `watch` callback is triggered, logging a change. This is crucial for scenarios where you need to react to any modification within a complex data structure without explicitly watching each individual nested property, ensuring your application remains responsive to state changes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs