動態(tài)路由

思路:

? ? 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
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容