How to Use onMounted in Vue
The onMounted lifecycle hook in Vue 3 Composition API is called after the component has been mounted to the DOM. As the creator of CoreUI with over 11 years of Vue.js development experience, I use onMounted for DOM manipulation, API calls, and third-party library initialization that requires the component to be fully rendered. This hook is the Composition API equivalent of the mounted lifecycle hook in Options API.
Use onMounted in the setup function to execute code after the component has been mounted to the DOM.
import { ref, onMounted } from 'vue'
export default {
setup() {
const users = ref([])
const loading = ref(false)
const chartContainer = ref(null)
onMounted(async () => {
console.log('Component mounted to DOM')
// API calls after mounting
loading.value = true
try {
const response = await fetch('/api/users')
users.value = await response.json()
} catch (error) {
console.error('Failed to fetch users:', error)
} finally {
loading.value = false
}
// DOM manipulation after mounting
if (chartContainer.value) {
initializeChart(chartContainer.value)
}
// Third-party library initialization
window.addEventListener('resize', handleResize)
})
const initializeChart = (container) => {
// Initialize chart library that requires DOM element
console.log('Initializing chart in:', container)
}
const handleResize = () => {
console.log('Window resized')
}
return {
users,
loading,
chartContainer
}
},
template: `
<div>
<div v-if="loading">Loading users...</div>
<div v-else>
<user-card v-for="user in users" :key="user.id" :user="user" />
</div>
<div ref="chartContainer" class="chart"></div>
</div>
`
}
The onMounted hook is called after the component’s template has been rendered and inserted into the DOM. It’s perfect for DOM manipulation, API calls, setting up event listeners, and initializing third-party libraries that need access to DOM elements. Use template refs to access specific DOM elements within onMounted. Remember to clean up event listeners and timers in onUnmounted to prevent memory leaks.
Best Practice Note:
In CoreUI components, we use onMounted extensively for chart initialization, form validation setup, and responsive design calculations that require actual DOM measurements. This ensures our components are fully functional immediately after rendering while maintaining optimal performance and proper resource management.



