Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define lifecycle methods in Vue 3 while using the <script setup> syntax?

I have defined a SFC similar to the one below

<script setup>
const msg = 'Hello World!'
const props = defineProps({....})
.....
function onMounted() {
    console.log('the component is now mounted')
}
</script>

<template>
    <p>{{ msg }}</p>
</template>

The onMounted function is not executing at all.

I wasn't able to find anything in the Vue documentation. Is it even possible to declare lifecycle hooks like this?

like image 527
Arjun Aravind Avatar asked Dec 30 '25 17:12

Arjun Aravind


1 Answers

SFC with the setup script is using the CompositionAPI, so you also have to define the livecycle hooks the same way:

import { onMounted } from 'vue'
onMounted(() => {
    console.log('mounted!')
})

https://v3.vuejs.org/api/composition-api.html#lifecycle-hooks

like image 116
Thomas Avatar answered Jan 02 '26 07:01

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!