Nuxt 3 动态路由无跳转渲染404页面的实现方法
在Nuxt3的兜底路由中无跳转渲染404页面
针对你的需求,不需要跳转路由,直接在[...slug]页面内根据API返回结果渲染404内容即可,以下是两种可行方案:
方案一:直接条件渲染自定义404内容
在页面组件中判断API返回的数据是否存在,不存在则直接显示404内容,同时设置正确的HTTP状态码保障SEO:
<template> <div v-if="data"> <!-- 正常数据内容渲染 --> <article>{{ data.content }}</article> </div> <div v-else class="not-found"> <h1>404 - 内容不存在</h1> <p>抱歉,未找到您请求的资源</p> <button @click="$router.push('/')">返回首页</button> </div> </template> <script setup> const route = useRoute() // 拼接slug参数请求API const { data } = await useFetch(`/api/resource/${route.params.slug.join('/')}`) // 无数据时设置404状态码和SEO元信息 if (!data.value) { useResponseStatus(404) useHead({ meta: [{ name: 'robots', content: 'noindex, nofollow' }] }) } </script>
方案二:结合Nuxt错误边界处理
利用Nuxt3的<NuxtErrorBoundary>组件捕获错误,主动抛出404错误后在当前页面展示错误内容:
<template> <NuxtErrorBoundary> <!-- 错误状态下的404内容 --> <template #error="{ error }"> <div class="not-found"> <h1>404 - 页面不存在</h1> <p>{{ error.message }}</p> </div> </template> <!-- 正常数据渲染区域 --> <div v-if="data"> <article>{{ data.content }}</article> </div> </NuxtErrorBoundary> </template> <script setup> const route = useRoute() const { data } = await useFetch(`/api/resource/${route.params.slug.join('/')}`) // 无数据时主动创建404错误 if (!data.value) { throw createError({ statusCode: 404, message: '抱歉,未找到您请求的资源' }) } // 捕获错误时设置404状态码 useError().value?.statusCode === 404 && useResponseStatus(404) </script>
关键注意点
- 必须使用
useResponseStatus(404)设置HTTP状态码,确保服务器端渲染时返回正确的404响应,避免影响SEO - 不要使用
navigateTo跳转404路由,保持当前路由路径不变,仅切换页面内容 - 如果需要复用404样式,可以将404内容抽离为单独组件(如
components/NotFound.vue),在需要的地方直接引入
内容的提问来源于stack exchange,提问作者Alexander Nortung
相关产品推荐
相关产品推荐

