vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3.0 No match found for location with path警告

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

作者:程序员Slute

这篇文章主要介绍了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}`)
      }

总结 

到此这篇关于Vue3.0动态路由No match found for location with path警告解决的文章就介绍到这了,更多相关Vue3.0 No match found for location with path警告内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文