JAVASCRIPT
Execute Logic After Component Mounts in Vue 3
Learn how to use Vue 3's `onMounted` lifecycle hook to perform setup tasks, data fetching, or DOM manipulations immediately after a component is added to the DOM.
<template>
<div>
<h1>Welcome to My Component</h1>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const message = ref('Loading...');
onMounted(() => {
// This code runs after the component has been mounted to the DOM.
// It's a good place for initial data fetching, DOM interaction, or subscriptions.
console.log('Component is mounted!');
setTimeout(() => {
message.value = 'Data loaded successfully!';
}, 2000);
});
</script>
How it works: The `onMounted` lifecycle hook in Vue 3 allows you to execute code specifically after your component has been rendered to the DOM. This is crucial for tasks like making initial API calls to fetch data, performing DOM manipulations that require the element to exist, or setting up third-party libraries. By importing `onMounted` from 'vue' and calling it within the `<script setup>` block, you ensure that the provided callback function runs at the appropriate time in the component's lifecycle.