Vue Router(路由) 如何配置 404 页面?
在 Vue Router 中配置 404页面(即匹配所有未定义路由的页面)主要通过通配符路由实现。
具体配置方法如下:
创建 404 页面组件
首先需要创建一个 404 页面组件,通常文件命名为 NotFound.vue
通常代码:
<template>
<diy class="not-found">
<h1>494</h1>
<p>页面不存在</p>
<router-link to="/">返回首页</router-link>
</div>
</template>
在路由配置中添加通配符路由
在 Vue Router 的路由配置中,添加一个通配符路由作为最后一个路由规则:
import { createRouter,createWebHistory } from 'vue-router'
import NotFound from "@/views/NotFound.vue"
const router = createRouter({
history: createWebHistory(),
routes:[
// 其他路由..
{ path: '/', component: Home },
{ path: '/about', component: About },
//404 路由配置-放在最后
{ path: '/:pathmatch(.*)*', name: 'NotFound', component: NotFound }
]
})
关键点是 path:'/:pathmatch(.*)*· 这个路径模式,它会匹配任何未被前面路由规则匹配的路径.
Vue Router 3.x与4.x的区别
在 Vue Router 3.x(用于 Vue 2)中,通配符路由的配置方式略有不同:
// Vue Router 3.x(Vue 2)
const router =new VueRouter({
routes:[
//其他路由...
{ path: '*', name: 'NotFound', component: NotFound }
]
})
而在 Vue Router 4.x(用于 Vue 3)中,使用的是参数化的通配符:
// Vue Router 4.x(Vue 3)
const router = createRouter({
// ...
routes:[
{ path: '/:pathmatch(.*)*', name: 'NotFound', component: NotFound }
]
})
通配符路由的高级用法
通配符路由还可以捕获未匹配的路径,并在组件中使用:
{ path: '/:pathmatch(.*)*', name: 'NotFound', component: NotFound }
在组件中可以通过$route.params.pathMatch 访问未匹配的路径部分:
<template>
<div>
<h1>页面不存在</h1>
<p>您访问的路径"{{ $route.params.pathMatch }}"不存在</p>
</div>
</template>
重定向到 404 页面的方式
除了直接使用通配符路由外,还可以使用重定向:
const router = createRouter({
// ...
routes:[
// 命名的 404 路由
{ path:'/404', name: 'NotFound', component: NotFound }
// 将所有未匹配的路由重定向到 404
{ path: '/:pathmatch(.*)*', redirect: {name: 'NotFound'} }
]
})
这种方式的好处是可以保持 URL的整洁(显示为 /404 而不是原始的未匹配路径)
动态导入 404 组件
为了优化性能,可以使用动态导入(懒加载)404 页面组件:
const router = createRouter({
// ...
routes:[
{
path: '/:pathmatch(.*)*',
name: 'NotFound',
component:()=>import('@/views/NotFound.vue')
}
]
})
路由守卫中处理 404
有时候我们需要在路由守卫中动态判断页面是否存在,例如基于后端 API的响应:
router.beforeEach(async (to,from,next)=>{
// 检查页面是否存在的逻辑
if(to.name !=='NotFound'){
try {
const pageExists =await checkIfPageExists(to.path)
if(!pageExists){
next({ name: 'NotFound' })
return
}
} catch (error) {
console.error(error)
}
}
next()
})
自定义错误页面
除了 404 页面,你还可以设置其他错误状态的页面,如 403(禁止访问)、500(服务器错误)等:
const router = createRouter({
history: createWebHistory(),
routes:[
// 其他路由...
// 403 页面
{ path: '/403', name: "Forbidden', component: () => import('@/views/Forbidden.vue') },
// 404 页面
{ path: '/404', name: 'NotFound', component: () => import('@/views/NotFound.vue') },
// 500 面
{ path: '/500',name: 'ServerError', component: () => import('@/views/ServerError.vue') },
// 通配符路由
{ path: '/:pathMatch(.*)*', redirect: { name:'NotFound' } }
]
})
Vue Router 官方文档地址:
路由匹配语法:
https://router.vuejs.org/zh/guide/essentials/route-matching-syntax.html
路由配置:
https://router.vuejs.org/zh/guide/essentials/dynamic-matching.html