[Vuejs]-How do I execute logic before a page/component is generated in Nuxt3 (lifecycle)?

0👍

If I understood your question correctly, using the basic v-if statement is enough to achieve your needs. You don’t need to use the life cycle hooks.

<script lang="ts" setup>
const userStatus = ref('authenticated')
</script>
<template>
    <div>
        <div v-if="userStatus === 'authenticated'">
            User is authenticated
        </div>
        <div v-else>
            User is not authenticated
        </div>
    </div>
</template>
<style scoped lang="css"></style>

If you really want to use the life cycle hooks, you can. Like this.

Note: onMounted and app:mounted hook are client only.

<script lang="ts" setup>
const userStatus = ref<boolean | null>(null)
const nuxtApp = useNuxtApp()
nuxtApp.hook('app:mounted', () => {
    userStatus.value = true
})
</script>
<template>
    <div>
        <div v-if="userStatus">
            User is authenticated
        </div>
        <div v-else>
            User is not authenticated
        </div>
    </div>
</template>
<style scoped lang="css"></style>

Though this will trigger the same effects as using the onMounted

const userStatus = ref<boolean | null>(null)
onMounted(() => {
    userStatus.value = true
})

I would recommend following the first example using the simple v-if statement as it supports SSR.

Leave a comment