-
首先,创建一个自定义的404页面组件和500页面组件。可以在项目中的某个目录下创建这两个组件文件,例如
NotFound.vue
和
ServerError.vue
。 -
在路由配置文件(通常是
router/index.js
)中,导入创建的自定义组件,并添加相应的路由配置。
import NotFound from '@/components/NotFound.vue'
import ServerError from '@/components/ServerError.vue'
const routes = [
// 其他路由配置...
{ path: '/404', component: NotFound },
{ path: '/500', component: ServerError },
{ path: '*', redirect: '/404' } // 配置通配符路由,用于匹配其他未定义的路由
]
const router = new VueRouter({
routes
})
export default router
3.在需要捕获404和500错误的地方,例如在主应用组件或者根组件中,可以添加一个路由守卫,通过判断错误类型来跳转到对应的自定义页面。
router.beforeEach((to, from, next) => {
if (to.matched.length === 0) { // 匹配不到路由
next('/404');
} else {
next();
}
})
4.在应用中的其他需要处理500错误的地方,例如在接口请求的错误处理函数中,可以通过跳转到
/500
路径来显示自定义的服务器错误页面。
axios.get('/api/xxx')
.then(response => {
// 处理正常响应
})
.catch(error => {
router.push('/500');
});
版权声明:本文为m0_73321385原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。