With following code sometimes I need to redirect to ‘/my/path’, and it works,
but before the redirect hits, user can see this page for few milliseconds (Text you shouldn’t see), and then they get redirected to ‘my/path’ as expected. But the problem here is how to prevent rendering of current page text, so user could only see ‘/my/path’
// page.vue
<script setup>
const someCondition = ....
if (someCondition) {
navigateTo({ path: '/my/path' }, { external: true })
}
// ... lots of some other stuff
</script>
<template>
Text you shouldn't see if someCondition is true
</template>
Had identical code in Nuxt 2, but it worked as expected.
UPD:
Rewrote code this way:
definePageMeta({
layout: false,
middleware: ['redir-to-mypath'],
})
<template>
<div v-if="!someCondition">
...
</div>
</template>
But it like changed nothing, leaaly confused here.
2
Answers
You can use
onBeforeMount
, which runs your condition before the DOM is generated. This likely was an issue with your old code, but something is different now – something is running a bit slower, your machine is a bit slower or you’re on a different one, etc.https://vuejs.org/api/composition-api-lifecycle.html#onbeforemount
Nuxt3 offers you the chance to set up a middleware which should exactly do what you are looking for.
Reference: https://nuxt.com/docs/guide/directory-structure/middleware
You can set up something like this:
Therefore you sort this out before the rendering of the page actually occurs.
Hope it helps