Blog>
Snippets

Deep Reactivity with Nested Objects

Demonstrate how Vue 3 handles reactivity in nested data objects using the `reactive` function from the Composition API.
<template>
  <div>
    <div>User Profile:</div>
    <div>Name: {{ userProfile.name }}</div>
    <div>Email: {{ userProfile.email }}</div>
    <div>Address: {{ userProfile.address.street }}</div>
    <button @click="updateAddress">Update Address</button>
  </div>
</template>

<script>
import { reactive, toRefs } from 'vue';
export default {
  setup() {
    // Using reactive to make the userProfile object deeply reactive
    const userProfile = reactive({
      name: 'Jane Doe',
      email: 'jane.doe@example.com',
      address: {
        street: '123 Main St',
        city: 'Anytown',
        zip: '12345'
      }
    });

    // Method to update a nested property
    function updateAddress() {
      userProfile.address.street = '456 Elm Street';
    }

    // Expose to template
    return { ...toRefs(userProfile), updateAddress };
  }
};
</script>
This Vue 3 component uses the Composition API to create deeply reactive data with nested objects. With the `reactive` function, changes to nested properties will still trigger reactivity and update the DOM when used in the template. The `toRefs` function is used to extract refs from the reactive object so they can be used directly in the template while maintaining reactivity. The `updateAddress` function demonstrates updating a nested property, which will automatically update the UI.
<style>
div {
  margin-bottom: 1rem;
}
button {
  padding: 0.5rem 1rem;
  font-size: 1rem;
  cursor: pointer;
}
</style>
This CSS styles the Vue component's divs and button, adding margins to the divs and styling the button to be more user-friendly with padding, font size adjustments, and a pointer cursor on hover.