思路:
1. 首先得设定一个layout主页面,动态路由只是动态子路由的权限控制。
2. 设立映射表,登录后,根据不同用户,后端返回对应的权限name路由表即可,然后通过映射表找出对应路由
3. 找到对应路由,存放到vuex或者Pinia中,调用异步路由加载方法生成新的路由数组layout,通过addRoute(layout)进行挂在。
// layout.vue
<container>
<header></header>
<container>
<aside></aside>
<main>
<el-tabs></el-tabs>
<router-view /> // 映射路由
</main>
</container>
</container>
...
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const allRouters: any = router.options.routes[0].children // 获取所有路由
// Login
import { setAsyncRoute } from '@/route'
setAsyncRoute(store.asyncRoute)
// main.js
import { setupRouter } from './router'
const app = createApp(App)
setupRouter(app)
// router/index.ts
import { mapRoutee } from './mapRoutes'
const common = [] // 通用路由,如首页什么的不需要权限控制的
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Layout',
redirect: '/home',
meta: {},
children: [...common]
},
{} // 登录
{} // 注册
404、401等
{
path: '/:catchAll(.*)', // 捕获不存在的路由
redirect: '404',
meta: { hide: true }
}
]// 路由守卫
function routerGuards(router: Router) {
router.beforeEach((to, from, next) => { do some thing })
}const router = createRouter({
history: createWebHashHistory(),
routes
})// 加载动态路由
export function setAsyncRoute(testRoute:any) {
const asyncRoute = mapRoutee(testRoute) // 获取映射路由
const layout:RouteRecordRaw = routes.find(i => i.name === 'Layout')
layout.children = [...common, ...asyncRoute]
router.addRoute(layout)
}// 挂载路由
export async fuunction setupRouter (app: App) {
routerGuards(router)
app.use(router)
// 等待路由准备就绪后挂载App实例
await router.isReady()
}export default router
// mapRouters.ts
const rMap = [] //动态映射路由
export function mapRoute(asyncRouter: any): any {
const arr: any[] = []
aysncRouter.map(item => {
rMap.map(i => {
item.name === i.name &&arr.push
})
})
return arr
}