What is onMounted in Vue: Explanation and Usage
onMounted is a Vue Composition API lifecycle hook that runs a function after the component is first added to the page (mounted). It lets you run code like fetching data or setting up events right after the component appears in the browser.How It Works
Think of onMounted as a moment when your component says, "I'm ready and visible now!" Just like when you move into a new house and want to set up your furniture, onMounted lets you run code right after the component shows up on the screen.
Under the hood, Vue waits until the component's HTML is fully inserted into the page. Then it runs the function you gave to onMounted. This is useful because some tasks, like talking to a server or measuring element sizes, only make sense once the component is visible.
Example
This example shows a simple Vue component that uses onMounted to set a message after the component appears.
import { ref, onMounted } from 'vue'; export default { setup() { const message = ref('Loading...'); onMounted(() => { message.value = 'Component is mounted and ready!'; }); return { message }; } };
When to Use
Use onMounted when you need to run code right after your component appears on the page. Common uses include:
- Fetching data from a server to show in the component
- Starting animations or timers
- Setting up event listeners that depend on the DOM
- Measuring element sizes or positions
It helps keep your setup code organized and ensures it runs at the right time.
Key Points
onMountedruns once after the component is inserted into the DOM.- It is part of Vue's Composition API for lifecycle management.
- Use it for tasks that require the component to be visible.
- It replaces the older
mountedoption in Options API.
Key Takeaways
onMounted runs code after the component is visible in the browser.onMounted to keep setup code organized and timed correctly.