Registering Lifecycle Hooks vue.js

The onMounted hook can be used to run code after the component has finished the initial rendering and created the DOM nodes:

vue

<script setup>
import { onMounted } from 'vue'

onMounted(() => {
  console.log(`the component is now mounted.`)
})
</script>

There are also other hooks which will be called at different stages of the instance’s lifecycle, with the most commonly used being onMountedonUpdated, and onUnmounted.

When calling onMounted, Vue automatically associates the registered callback function with the current active component instance. This requires these hooks to be registered synchronously during component setup. For example, do not do this:

js

setTimeout(() => {
  onMounted(() => {
    // this won't work.
  })
}, 100)

Do note this doesn’t mean that the call must be placed lexically inside setup() or <script setup>onMounted() can be called in an external function as long as the call stack is synchronous and originates from within setup().

Leave a comment

Your email address will not be published. Required fields are marked *