Blog>
Snippets

Deep reactivity with reactive objects

Showcase how to create a deeply reactive object using 'reactive' and illustrate how changes to nested properties are tracked.
<div id="app"></div>
This is the HTML structure that will display the reactive data. It includes a single div element with the id 'app' which serves as a mount point for our JavaScript code.
/* Global reactive data object */
const reactiveData = Vue.reactive({
  message: 'Hello',
  user: {
    name: 'Alice',
    details: {
      age: 25,
      location: 'Wonderland'
    }
  }
});

/* Watching for deep changes */
Vue.watch(
  reactiveData,
  (newValue, oldValue) => {
    console.log('Change detected:', newValue);
  },
  { deep: true }
);

/* Changing nested property to trigger reactive changes */
setTimeout(() => {
  reactiveData.user.details.age = 26;
}, 1000);
This piece of JavaScript utilizes Vue 3's Composition API to create a deeply reactive object called 'reactiveData'. We use Vue's 'reactive' method to make our data object reactive. We then set up a watcher with the 'watch' method, specifying the 'deep' option in order to detect changes on nested properties. Finally, we simulate a deep change by modifying the 'age' property inside a nested object after 1 second.
/* Vue app setup */
const App = {
  setup() {
    /* Exposing reactiveData to the template */
    return { reactiveData };
  }
};

Vue.createApp(App).mount('#app');
This JavaScript code sets up a new Vue application using the Composition API 'setup' function and mounts it to the div with id 'app'. The reactive data object created earlier is exposed to the template so it can be displayed and react to changes.
#app {
  padding: 20px;
  font-family: Arial, sans-serif;
}

/* Styling just to make the example visually appealing */
CSS styles for the 'app' div element. These styles apply padding and font-family to make the example visually presentable.