Blog>
Snippets

Reactivity and Lifecycle Hooks

Use Vue's lifecycle hooks like `onMounted` and `onUpdated` to perform actions in a component's lifecycle, observing reactivity.
<template>
  <div>
    <h1>{{ message }}</h1>
    <button @click="updateMessage">Change Message</button>
  </div>
</template>

<script setup>
import { ref, onMounted, onUpdated } from 'vue';

const message = ref('Hello, Vue 3!'); // Declare a reactive state

// Lifecycle hook - onMounted
onMounted(() => {
  console.log('Component is mounted!');
  // This will be executed when the component is added to the DOM
});

// Lifecycle hook - onUpdated
onUpdated(() => {
  console.log('Component has been updated!');
  // This will be executed whenever the component's reactive dependencies change
});

// Method to update the reactive message
const updateMessage = () => {
  message.value = 'Message updated!';
  // Changing the message will trigger onUpdated lifecycle hook
};
</script>

<style scoped>
h1 {
  color: #42b983;
}
</style>
This Vue component uses the onMounted and onUpdated lifecycle hooks to react to lifecycle events. On mount, a message saying 'Component is mounted!' will be logged, indicating the component has been added to the DOM. The onUpdated hook logs a message indicating the component has updated whenever a reactive dependency changes. In this case, clicking the button updates the 'message' reactive data, which triggers the onUpdated hook and logs the update to the console.