N
Nuxt4w ago
Joni

Have multiple layouts for one page depending on condition

I have a terms and conditions page, it should be viewed when logged in and not logged in. Unfortunately, I can't assign a condition to it Error: "layout is not defined"
const userStore = useUserStore();

const {
userIsLoggedIn,
userHasAcceptedTerms,
storeIsLoading,
} = storeToRefs(userStore);

const layout = computed(() => {
return userIsLoggedIn?.value ? 'default' : 'no-auth';
});

definePageMeta({
layout // OR : userIsLoggedIn?.value ? 'default' : 'no-auth' // "userIsLoggedIn is not defined"
})
const userStore = useUserStore();

const {
userIsLoggedIn,
userHasAcceptedTerms,
storeIsLoading,
} = storeToRefs(userStore);

const layout = computed(() => {
return userIsLoggedIn?.value ? 'default' : 'no-auth';
});

definePageMeta({
layout // OR : userIsLoggedIn?.value ? 'default' : 'no-auth' // "userIsLoggedIn is not defined"
})
Thanks in advance!
3 Replies
Cue
Cue4w ago
definePageMeta is a compiler macro. Referencing a variable that hasn’t yet been instantiated when this function is declared will result in it being undefined. For the sake of “use this layout if the user is logged in”, pass computed as name prop to NuxtLayout
akaSECTION
akaSECTION4w ago
you can also use setPageLayout function dynamically at runtime, but if you do that after mounted, you will get a slight blank display until the layout is fetched (unless you find the way to preload the layout first)
Joni
Joni4w ago
Thank you guys, ofc i googled but didnt really know what to google... Thats the thing cuebit talked about
<script setup lang="ts">
// You might choose this based on an API call or logged-in status
const layout = "custom";
</script>

<template>
<NuxtLayout :name="layout">
<NuxtPage />
</NuxtLayout>
</template>
<script setup lang="ts">
// You might choose this based on an API call or logged-in status
const layout = "custom";
</script>

<template>
<NuxtLayout :name="layout">
<NuxtPage />
</NuxtLayout>
</template>
And thats what akasection talked about
<script setup lang="ts">
function enableCustomLayout () {
setPageLayout('custom')
}
definePageMeta({
layout: false,
});
</script>

<template>
<div>
<button @click="enableCustomLayout">Update layout</button>
</div>
</template>
<script setup lang="ts">
function enableCustomLayout () {
setPageLayout('custom')
}
definePageMeta({
layout: false,
});
</script>

<template>
<div>
<button @click="enableCustomLayout">Update layout</button>
</div>
</template>
Want results from more Discord servers?
Add your server