vue router 默认路由,匹配所有路由到 404 页面

vue2 + vue-router

const needLoginRoutes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/home',
    redirect: '/'
  }
]

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/404.vue')
  },
  {
    path: '/manage-*', // 匹配所有以manage开头的路由
    name: 'Manage',
    component: () => import('../views/manage.vue')
  },
  {
    path: '*', // 匹配所有路由
    redirect: '/404'
  }
]

需要注意,匹配所有要放到最后,因为路由是从上往下匹配,匹配到一个后就会停止,如果把加 * 号的路由写到上边,可能会引发死循环

所以,如果你只有一个页面,希望用户所有的路径都匹配到某页面就可以这样写

const routes = [
    {
        path: '/xxx',
        name: 'Xxx',
        component: () => import('../Xxx')
    },
    {
        path: '*',
        redirect: '/xxx'    
    }
]

==========

需要注意的是 vue3 + vue-router

vue-router 把 * 这种写法废弃了,如果需要匹配所有,需要写成这样

const routes = [
  // pathMatch是参数的名称,例如,要去/not/found
  // { params: { pathMatch: ['not', 'found'] }}

  // 最后一个*,它意味着重复的参数,如果您打算使用它的名称直接导航到未找到的路由,那么这是必要的
  { path: '/:pathMatch(.*)*', name: 'not-found', component: NotFound },

  // 如果你省略了最后一个' * ',参数中的' / '字符将在解析或推入时被编码
  { path: '/:pathMatch(.*)', name: 'bad-not-found', component: NotFound },
]

参考链接:https://next.router.vuejs.org/guide/migration/index.html#moved-the-base-option

 

 

 

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值