javascript Nuxt 3 -在脚本设置中重定向

f45qwnt8  于 12个月前  发布在  Java
关注(0)|答案(3)|浏览(137)

下面的代码有时我需要重定向到'/my/path',它工作,但在重定向命中之前,用户可以看到这个页面几毫秒(你不应该看到的文本),然后他们被重定向到'my/path'。但这里的问题是如何防止呈现当前页面文本,因此用户只能看到'/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>

在Nuxt 2中有相同的代码,但它按预期工作。
UPD:
这样重写代码:

definePageMeta({
  layout: false,
  middleware: ['redir-to-mypath'],
})
<template>
  <div v-if="!someCondition">
  ...
  </div>
</template>

但它像什么都没改变,lealy困惑在这里。

nszi6y05

nszi6y051#

Nuxt3为您提供了设置中间件的机会,该中间件应该完全符合您的要求。
参考:https://nuxt.com/docs/guide/directory-structure/middleware
你可以这样设置:

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`)
   }

 })

因此,在实际呈现页面之前,您就可以解决这个问题。
希望它能帮助

shstlldc

shstlldc2#

您可以使用onBeforeMount,它在生成DOM之前运行您的条件。这可能是你的旧代码的问题,但是现在有些不同了--有些东西运行得有点慢,你的机器有点慢,或者你在一个不同的机器上,等等。
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>
gdrx4gfi

gdrx4gfi3#

使用中间件是最好的选择。
页面定义的中间件,例如

<script lang="ts" setup>
definePageMeta({
  middleware: [
    function(to, from) {
      // Run your conditions here.
    }
  ]
})
</script>

如果你真的不想使用中间件,你可以使用page:finish钩子。

<script lang="ts" setup>
const displayContent = ref(false)
if (someCOndition) {
  navigateTo('/')
}
onMounted(() => {
  useNuxtApp().hook('page:finish', () => {
    displayContent.value = true
  })
})
</script>
<template>
  <div v-if="displayContent">
    <!-- Start of content -->
  </div>
</template>

相关问题