skip to Main Content

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


  1. 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

    <script setup>
    import { onBeforeMount } from "vue";
    
    onBeforeMount(() => {
        if (someCondition) navigateTo({ path: '/my/path' }, { external: true }) ;
    });
    </script>
    
    Login or Signup to reply.
  2. 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:

    export default defineNuxtRouteMiddleware((to: any, from: any) => {
        const nuxtApp = useNuxtApp()
    
        if(process.server) {    
            host = nuxtApp.ssrContext?.event.node.req.headers.host
        } else {
            host = window.location.host
        }
    
       if(host.indexOf('xyz') < 0) {
           return navigateTo(`/xyz/test`)
       }
    
     })
    

    Therefore you sort this out before the rendering of the page actually occurs.

    Hope it helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search