思路:
? ? 1. 首先得設(shè)定一個layout主頁面,動態(tài)路由只是動態(tài)子路由的權(quán)限控制。
? ? 2. 設(shè)立映射表,登錄后,根據(jù)不同用戶,后端返回對應(yīng)的權(quán)限name路由表即可,然后通過映射表找出對應(yīng)路由
? ? 3. 找到對應(yīng)路由,存放到vuex或者Pinia中,調(diào)用異步路由加載方法生成新的路由數(shù)組layout,通過addRoute(layout)進(jìn)行掛在。
// 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 = [] // 通用路由,如首頁什么的不需要權(quán)限控制的
const routes: Array<RouteRecordRaw> = [
? ? {
? ? ? ? path: '/',
? ? ? ? name: 'Layout',
? ? ? ? redirect: '/home',
? ? ? ? meta: {},
? ? ? ? children: [...common]
????},
? ? {} // 登錄
? ? {} // 注冊
? ? 404、401等
????{
? ? ? ? path: '/:catchAll(.*)', // 捕獲不存在的路由
? ? ? ? redirect: '404',
? ? ? ? meta: { hide: true }? ??
????}
]// 路由守衛(wèi)
function routerGuards(router: Router) {
? ? router.beforeEach((to, from, next) => { do some thing })
}const router = createRouter({
? ? history: createWebHashHistory(),
? ? routes
})// 加載動態(tài)路由
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)
? ? // 等待路由準(zhǔn)備就緒后掛載App實例
? ? await router.isReady()
}export default router
// mapRouters.ts
const rMap = [] //動態(tài)映射路由
export function mapRoute(asyncRouter: any): any {
? ? const arr: any[] = []
? ? aysncRouter.map(item => {
? ? ? ? rMap.map(i => {
? ? ? ? ? ? item.name === i.name &&arr.push
????????})
????})
? ? return arr
}