JAVASCRIPT

Deep Watching Reactive Objects in Vue 3 `watch`

Learn to effectively monitor nested changes within reactive objects in Vue 3 using the `watch` function with the `deep` option in the Composition API.

// components/UserDetails.vue
<template>
  <div>
    <h2>User Details</h2>
    <p>Name: {{ user.name.first }} {{ user.name.last }}</p>
    <p>Age: {{ user.age }}</p>
    <button @click="changeFirstName">Change First Name</button>
    <button @click="incrementAge">Increment Age</button>
    <button @click="changeAddressCity">Change Address City</button>
    <p><i>Check console for watch logs.</i></p>
  </div>
</template>

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

const user = reactive({
  name: {
    first: 'John',
    last: 'Doe'
  },
  age: 30,
  address: {
    street: '123 Vue St',
    city: 'Vueville'
  }
});

// Watch the entire 'user' object deeply
watch(user, (newValue, oldValue) => {
  console.log('User object changed (deep watch):', newValue);
  console.log('Old User object:', oldValue);
}, { deep: true });

// You can also watch a specific nested property if only that matters
watch(() => user.age, (newAge, oldAge) => {
  console.log('User age changed:', newAge, 'from', oldAge);
});

const changeFirstName = () => {
  user.name.first = 'Jane';
};

const incrementAge = () => {
  user.age++;
};

const changeAddressCity = () => {
  user.address.city = 'Nuxt City';
};
</script>

// App.vue
<template>
  <UserDetails />
</template>

<script setup>
import UserDetails from './components/UserDetails.vue';
</script>
How it works: This snippet demonstrates how to use Vue 3's `watch` function to react to changes within a reactive object, specifically focusing on 'deep' watching. By passing `{ deep: true }` as an option to `watch`, any nested property changes within the `user` reactive object will trigger the watcher callback. This is crucial when you need to perform side effects or computations not just when the top-level reference changes, but also when internal properties of a complex object are modified.

Need help integrating this into your project?

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

Hire DigitalCodeLabs