onMounted and onBeforeMount
Accessing the DOM in onMounted, why onBeforeMount rarely needs direct use.
Hooks Around Mounting
The mounting phase has two hooks: onBeforeMount fires just before the DOM is created, and onMounted fires right after it is inserted. They look similar but serve very different needs.
onMounted: The DOM Is Ready
By the time onMounted runs, the component template has rendered and is in the page. Template refs point to real elements, so this is where DOM work belongs.
<script setup>
import { ref, onMounted } from 'vue'
const box = ref(null)
onMounted(() => {
console.log(box.value.offsetWidth)
})
</script>All lessons in this course
- Lifecycle Phases Overview
- onMounted and onBeforeMount
- onUpdated and onBeforeUpdate
- onUnmounted and Cleanup Patterns