JAVASCRIPT

Leveraging Vue 3 Lifecycle Hooks in Composition API

Learn to use essential lifecycle hooks like `onMounted`, `onUpdated`, and `onUnmounted` within Vue 3's Composition API to execute code at specific stages of a component's existence.

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

const dynamicText = ref('Initial Text');

onMounted(() => {
  console.log('Component is mounted! DOM is available.');
  // Example: Fetch data, subscribe to events
  document.title = 'Vue 3 Mounted!';
});

onUpdated(() => {
  console.log('Component has updated! Reactive data changed.');
  // Example: Respond to DOM changes after reactive data updates
  // Be cautious to avoid infinite update loops
});

onUnmounted(() => {
  console.log('Component is unmounted! Cleanup tasks.');
  // Example: Unsubscribe from events, clear timers
  document.title = 'Vue 3 Unmounted!';
});

function changeText() {
  dynamicText.value = 'Text updated at ' + new Date().toLocaleTimeString();
}
</script>

<template>
  <div>
    <h1>Lifecycle Hooks Demo</h1>
    <p>{{ dynamicText }}</p>
    <button @click="changeText">Update Text</button>
  </div>
</template>
How it works: This snippet illustrates how to integrate Vue 3's lifecycle hooks with the Composition API using the `setup` script. `onMounted` is called after the component has been mounted to the DOM, making it ideal for initial data fetching or DOM manipulations. `onUpdated` is invoked after the component has re-rendered due to a reactive state change. `onUnmounted` runs just before the component is destroyed and removed from the DOM, perfect for cleanup operations like unsubscribing from event listeners or clearing timers, preventing memory leaks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs