解决Vue3.0 动态路由 No match found for location with path 警告

在Vue3中使用router.addRoute动态添加路由时,由于路由添加是异步的,第一次不会匹配到未添加的路由导致警告,先把404写在固定路由里面,用来捕获第一次未匹配到的路由,就不会有警告了,但是会出现一刷新就跳转404

{
    path: '/404',
    name: '404',
    component: () => import('@/views/error/404.vue'),
    hidden: true,
    meta: { title: "找不到此页面" }
  },
  {
    path: '/:pathMatch(.*)',
    name: 'notFound',
    hidden: true,
    redirect: '/404',
  },

所以在router.beforeEach里面需要判断一下,userPermissionsStore是使用了pinia存routes

    try {
        const permissionsState = userPermissionsStore()

        // 判断是否添加成功
        // permissionsState.routes的数据在permissionsState.getRoutes()中设置
        if (!permissionsState.routes.length) {

          // 获取要加载的路由
          const accessRoutes = await permissionsState.getRoutes()
          accessRoutes.forEach((item) => router.addRoute(item)) 
          
          // 这里是核心代码,因为第一次匹配不到会跳转404
          // 所以跳转到404的时候再做一个操作
          if (to.path == '/404' && to.redirectedFrom) {
            next({ path: to.redirectedFrom.fullPath, replace: true })
          } else {
            next({ ...to, replace: true }) // 这里相当于push到一个页面 不在进入路由拦截
          }
        } else {
          next()   // 如果不传参数就会重新执行路由拦截,重新进到这里
        }
      } catch (err) {
        next(`/login?redirect=${to.path}`)
      }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值