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

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

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

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

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页面。

猜你喜欢

转载自blog.csdn.net/weixin_37861326/article/details/82383465