Search code examples
vue.jsvuejs3vue-sfc

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?


Solution

  • 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