共计 945 个字符,预计需要花费 3 分钟才能阅读完成。
在 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 警告
正文完