需要将任意路由 path: '/:pathMatch(.*)*'
从固定路由中提取出来,在刷新时,等待用户信息获取完毕,将动态路由和任意路由通过 router.addRoute()
重新添加到路由中
// 固定路由
export const constantRoute = [ ... ]
// 权限路由
export const asyncRoute = [...]
// 任意路由(404路由可放在任意路由或固定路由中)
export const anyRoute = [
{
path: '/:pathMatch(.*)*',
redirect: '/404',
name: 'any',
// 通过 meta 可用于菜单展示判断
meta: {
title: '任意路由',
hidden: true,
}
}
]
刷新时执行,可在pinia(或vuex)中实现
userInfo(){
...
// 获取用户信息,并从中提取动态路由 userAsyncRoute
// 用于菜单展示,anyRoute可加可不加
menuRoutes = [...constantRoute, ...userAsyncRoute, ...anyRoute];
// 将anyRoute、userAsyncRoute添加到路由中
[ ...anyRoute, ...userAsyncRoute].forEach((route: any) => {
router.addRoute(route)
})
}
路由守卫,可在permission.js中实现
//全局前置守卫
router.beforeEach(async (to, from, next) => {
...
// 等待用户信息加载完毕
await userInfo()
// 异步路由刷新,获取到用户信息时,异步路由还没有加载完毕,出现空白的效果
// hack方法,确保addRoutes已完成
next({ ...to, replace: true })
...
})