← Back to all snippets
JAVASCRIPT

Utilizing Vue 3 Lifecycle Hooks in Composition API

Discover how to use Vue 3's Composition API lifecycle hooks like `onMounted`, `onUpdated`, and `onUnmounted` to execute code at specific component stages.

import { ref, onMounted, onUpdated, onUnmounted } from 'vue';

export default {
  setup() {
    const message = ref('Hello Vue 3!');

    onMounted(() => {
      console.log('Component is mounted to the DOM.');
      // Perform initial data fetching or DOM manipulation here
    });

    onUpdated(() => {
      console.log('Component just updated due to reactive data change.');
      // React to DOM updates here
    });

    onUnmounted(() => {
      console.log('Component is about to be unmounted from the DOM.');
      // Clean up side effects like timers, event listeners here
    });

    // Change message after 2 seconds to trigger onUpdated
    setTimeout(() => {
      message.value = 'Updated Vue 3 message!';
    }, 2000);

    return {
      message
    };
  }
};

/*
<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>
*/
How it works: This snippet illustrates the use of Vue 3's lifecycle hooks within the Composition API. `onMounted` runs after the component is first rendered. `onUpdated` triggers whenever the component's reactive data causes a re-render. `onUnmounted` executes just before the component is removed from the DOM. These hooks are crucial for managing side effects and resources throughout a component's lifespan.

Need help integrating this into your project?

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

Hire DigitalCodeLabs