使用 notFound 路由配置
Vue Router 4 及更高版本提供了一个 notFound 选项,你可以在创建路由器实例时使用它来指定一个 404 页面:
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import NotFound from './views/NotFound.vue';
const routes = [
// ... 其他路由配置
];
const router = createRouter({
history: createWebHistory(),
routes: [
...routes,
{
path: '/:catchAll(.*)', // 使用 catchAll 捕获所有未匹配的路由
name: 'NotFound',
component: NotFound
}
],
notFound: {
component: NotFound // 指定 404 页面组件
}
});
export default router;
使用重定向
在 Vue Router 3 或者不支持 notFound 选项的版本中,你可以使用重定向来实现类似的效果:
import Vue from 'vue';
import Router from 'vue-router';
import Home from './components/Home.vue';
import NotFound from './components/NotFound.vue';
Vue.use(Router);
const router = new Router({
mode: 'history',
routes: [
{ path: '/', component: Home },
// ... 其他路由配置
{ path: '*', redirect: '/404' } // 捕获所有未匹配的路由并重定向到 404 页面
]
});
router.afterEach((to, from) => {
if (to.path.startsWith('/404') && !to.matched.length) {
// 显示 404 页面
}
});
export default router;
监听路由变化
监听路由变化,并在没有匹配的路由时显示 404 页面:在路由守卫中检查当前的路由是否有匹配的组件,如果没有,就重定向到 404 页面。
router.beforeEach((to, from, next) => {
if (to.matched.length === 0) {
// 没有匹配的路由,重定向到 404 页面
to.path = '/404';
}
next();
});