VUE3中路由采用动态加载的模式下,当我们在当前页面刷新浏览器时,会出现一个警告
[Vue Router warn]: No match found for location with path
警告的意思是提示当前路由并不存在,刷新时此路由确实不存在,因为在路由鉴权中beforeEach时,动态路由并未加载。
虽然,我们添加了动态路由后再 replace: true 跳转一次,但这个警告每次看到就难受。
那么处理的方式分为2个步骤:
1、我们在router/index.js 中:
const { name } = router.currentRoute.value
if (!name) {
router.addRoute({
path: window.location.pathname,
name: 'TempRoute',
component: () => import('@/components/layouts/emptyLayout.vue')
})
}
export default router
2、在路由鉴权中router/routeAuth.js 在后端返回动态路由并addRoute之后添加以下代码:
// 授权成功执行以下代码
// 存在临时路由则先删除临时路由
const tempRoute = router.hasRoute('TempRoute')
if (tempRoute) router.removeRoute('TempRoute')
const { accessedRoutes, defaultRoute } = await store.dispatch('routes/setAsyncRoutes', { loading: false })
accessedRoutes.forEach(route => router.addRoute(route))
if (to.path === '/' && defaultRoute && defaultRoute.path !== '/') {
return next({ path: defaultRoute.path, replace: true })
}
// 此时已添加了后端返回的动态路由,进行跳转一次
if (tempRoute) {
// 此处 next 里就不可用 ...to,因为 to 是临时路由
next({ path: to.path, query: to.query, replace: true })
} else {
next({ ...to, replace: true })
}