Vue Router 的通配符路由无法捕获已匹配动态路径(如 /movie/a615656)的 404 场景,因其仍满足 /movie/:id 模式;真正有效的 404 处理需结合路由守卫、服务端响应校验与错误重定向三重机制。
vue router 的通配符路由无法捕获已匹配动态路径(如 `/movie/a615656`)的 404 场景,因其仍满足 `/movie/:id` 模式;真正有效的 404 处理需结合路由守卫、服务端响应校验与错误重定向三重机制。
在 Vue 3 + Vue Router 4 的单页应用中,/:pathMatch(.*)* 通配符路由仅对完全未匹配的路径生效——它不会干预已被显式定义的动态路由(如 /movie/:id)。因此,当用户访问 http://localhost:8080/movie/a615656 时,Router 会成功匹配 movie_details 路由,根本不会进入 404 路由逻辑。此时若该 ID 在 TMDB API 中不存在,前端必须主动识别并跳转至 404 页面,而非依赖路由配置自动兜底。
通配符路由必须置于所有具名路由之后,且使用标准 Vue Router 4 语法:
// src/router/index.tsconst routes: RouteRecordRaw[] = [ { path: '/', name: 'home', component: HomeView }, { path: '/top-rated', name: 'top_rated', component: TopRatedMoviesView }, { path: '/movie/:id', name: 'movie_details', component: MovieDetailsView }, { path: '/actor/:id', name: 'actor_details', component: ActorDetailsView }, // ✅ 必须放在最后,且 path 为严格通配 { path: '/:pathMatch(.*)*', name: 'not-found', component: NotFoundView, meta: { hidden: true } // 可选:避免出现在菜单 }]
⚠️ 注意:name: '404' 不推荐——易与 HTTP 状态码混淆,且 Vue Router 要求 name 全局唯一;建议统一用 not-found 或 404-page。
在 MovieDetailsView.vue 中,通过 useRoute() 获取 id,调用 API 后根据响应状态决定是否跳转:
立即学习“前端免费学习笔记(深入)”;
<!-- src/views/MovieDetailsView.vue --><script setup lang="ts">import { useRoute, useRouter } from 'vue-router'import { onMounted } from 'vue'import { fetchMovieById } from '@/api/tmdb'const route = useRoute()const router = useRouter()const movie = ref<any>(null)onMounted(async () => { try { const id = route.params.id as string // ✅ 关键:校验 ID 格式(可选增强) if (!/^d+$/.test(id)) { await router.push({ name: 'not-found' }) return } movie.value = await fetchMovieById(id) } catch (err: any) { // ✅ 关键:捕获 API 404 响应 if (err.response?.status === 404 || err.message?.includes('404')) { await router.push({ name: 'not-found' }) } else { console.error('Failed to load movie:', err) // 可选:跳转通用错误页或显示 Toast } }})</script>
若多个动态路由需共用 404 逻辑,可在 router.beforeEach 中集中处理:
// src/router/index.tsrouter.beforeEach(async (to, from, next) => { // 仅对含 :id 参数的动态路由启用校验 if (to.name === 'movie_details' || to.name === 'actor_details') { try { const id = to.params.id as string const apiPath = to.name === 'movie_details' ? `/movie/${id}` : `/person/${id}` const res = await fetch(`/api/tmdb${apiPath}`).then(r => r.json()) if (!res.success && res.status_code === 34) { // TMDB 404 code is 34 next({ name: 'not-found' }) return } } catch (e) { next({ name: 'not-found' }) return } } next()})
/:pathMatch(.*)* 是“路径未命中”的兜底,而 /movie/:id 下的 404 是“资源不存在”的业务错误——二者语义不同,必须分层处理。真正的健壮方案 = 通配符路由(兜底非法路径) + 动态组件内 API 错误捕获(处理资源缺失) + 可选全局守卫(统一策略)。唯有如此,才能确保 http://localhost:8080/movie/999999999 和 http://localhost:8080/xyz 均能优雅呈现 404 视图。