您的位置:首页 > Web前端 > Vue.js

vue项目中路由不匹配或者路径错误,添加默认404页面的方法

2018-09-04 14:50 483 查看

在Vue项目中,当访问的页面路由不存在或错误时,页面显示为一片空白。然而,通常我们需要对访问url不存在或者错误的情况下添加默认的404页面,即not found页面。处理方法如下,在router中添加方法:

[code]router.beforeEach((to, from, next) => {
if (to.matched.length === 0) { //匹配前往的路由不存在
from.name ? next({
name: from.name
}) : next('/errorinfo'); //判断此跳转路由的来源路由是否存在,存在的情况跳转到来源路由,否则跳转到404页面
} else {
next(); //如果匹配到正确跳转
}
});

完整的路由配置文件如下:

[code]import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
// 404
import Errorinfo from '@/components/error404'

const router = new Router({
routes: [
// 404page
{
path: '/errorinfo',
name: 'Errorinfo',
component: Errorinfo
}
],
scrollBehavior(to, from, savedPosition) {
return {
x: 0,
y: 0
}
},
history: true
})
router.beforeEach((to, from, next) => {
if (to.matched.length === 0) {
from.name ? next({
name: from.name
}) : next('/errorinfo');
} else {
next(); //如果匹配到正确跳转
}
});
export default router;

通过上述方式即可添加404页面。

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐