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

Time:10-19

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?

CodePudding user response:

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

  • Related