vue實(shí)現(xiàn)前端控制動(dòng)態(tài)路由的示例代碼
在 Vue.js 中,動(dòng)態(tài)路由是一種根據(jù)不同用戶(hù)權(quán)限或其他因素動(dòng)態(tài)改變路由列表的功能。這種機(jī)制允許開(kāi)發(fā)者根據(jù)后端提供的權(quán)限數(shù)據(jù)動(dòng)態(tài)渲染前端路由,實(shí)現(xiàn)多用戶(hù)權(quán)限系統(tǒng),不同用戶(hù)展示不同的導(dǎo)航菜單。
動(dòng)態(tài)路由的配置
動(dòng)態(tài)路由的配置涉及到前端路由的動(dòng)態(tài)加載和解析。通常,動(dòng)態(tài)路由的數(shù)據(jù)存儲(chǔ)在數(shù)據(jù)庫(kù)中,前端通過(guò)接口獲取當(dāng)前用戶(hù)對(duì)應(yīng)的路由列表并進(jìn)行渲染。以下是實(shí)現(xiàn)動(dòng)態(tài)路由的基本步驟:
靜態(tài)路由配置:首先,需要配置靜態(tài)路由,如登錄頁(yè)、首頁(yè)等。這些路由通常不會(huì)改變,可以直接寫(xiě)在路由配置文件中。
// 創(chuàng)建路由實(shí)例
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: allRoutes
})// 所有路由定義(靜態(tài)+動(dòng)態(tài))
const allRoutes = [
// 基礎(chǔ)路由
{
path: '/',
name: 'login',
component: () => import("@/views/LoginView.vue")
},
{
path: '/404',
name: '404',
component: () => import('@/views/Error/404View.vue')
},
// 動(dòng)態(tài)路由容器(登錄后內(nèi)容)
{
path: '/layout',
name: 'layout',
component: () => import('@/Layout/MainLayout.vue'),
children: [] // 初始為空,動(dòng)態(tài)注入路由
},
]動(dòng)態(tài)路由獲取:在用戶(hù)登錄后,前端調(diào)用后端接口獲取用戶(hù)對(duì)應(yīng)的權(quán)限類(lèi)型role。
// 需要權(quán)限控制的路由配置(扁平化結(jié)構(gòu)更易管理)
const dynamicRouteConfigs = [
{
path: '/home', // 注意使用相對(duì)路徑
name: 'home',
component: () => import('@/views/HomeView.vue'),
meta: {
title: '首頁(yè)',
icon: 'House',
roles: ['*'] // *表示所有登錄用戶(hù)
}
},
{
path: 'user/list',
name: 'UserList',
component: () => import('@/views/user/ListView.vue'),
meta: {
title: '用戶(hù)列表',
roles: ['1','2']
}
},
{
path: 'user/role',
name: 'UserRole',
component: () => import('@/views/user/RoleView.vue'),
meta: {
title: '角色管理',
roles: ['1']
}
}
]路由過(guò)濾的函數(shù)
// 權(quán)限過(guò)濾方法修正
const filterRoutes = (routes, roles) => {
// 遞歸處理每個(gè)路由節(jié)點(diǎn)
return routes.filter(route => {
// 獲取當(dāng)前路由需要的權(quán)限角色
const requiredRoles = route.meta?.roles || []
// 檢查當(dāng)前路由是否滿(mǎn)足權(quán)限要求
const hasPermission = requiredRoles.includes('*') || requiredRoles.includes(roles + '')
// 遞歸處理子路由(關(guān)鍵修改點(diǎn))
if (route.children) {
const filteredChildren = filterRoutes(route.children, roles)
// 保留有效子路由:只有當(dāng)子路由存在時(shí)才保留children
route.children = filteredChildren.length ? filteredChildren : undefined
}
/*
路由保留條件(核心邏輯):
1. 當(dāng)前路由自身有權(quán)限 或
2. 存在有效的子路由(即使當(dāng)前路由沒(méi)有權(quán)限,但子路由有權(quán)限時(shí)保留父級(jí)容器)
*/
return hasPermission || (route.children && route.children.length > 0)
})
}動(dòng)態(tài)添加路由,先清空已有的動(dòng)態(tài)路由,然后再調(diào)用添加路由的函數(shù)進(jìn)行添加,
// 動(dòng)態(tài)添加路由到layout
const addDynamicRoutes = (roles) => {
// 清空已有動(dòng)態(tài)路由
const layout = router.getRoutes().find(r => r.name === 'layout')
layout.children.forEach(child => {
router.removeRoute(child.name)
})
// 過(guò)濾并添加新路由
const allowedRoutes = filterRoutes(dynamicRouteConfigs, loginStore().roles);
allowedRoutes.forEach(route => { router.addRoute('layout', route); });
console.log(allowedRoutes);
sessionStorage.setItem('menuPath',JSON.stringify(allowedRoutes));//存儲(chǔ)的篩選過(guò)的動(dòng)態(tài)路由
sessionStorage.setItem('menuName',JSON.stringify(router.getRoutes()));//存儲(chǔ)的所有動(dòng)態(tài)路由
console.log(router.getRoutes());
// 確保404最后處理
router.addRoute({
path: '/:pathMatch(.*)*',
redirect: '/404'
})
}導(dǎo)航守衛(wèi)部分,路由跳轉(zhuǎn)前的操作。
獲取用戶(hù)狀態(tài)存儲(chǔ)實(shí)例,檢測(cè)登錄狀態(tài);判斷用戶(hù)未登錄時(shí)直接跳轉(zhuǎn)到登錄頁(yè)進(jìn)行登錄;已登錄訪問(wèn)登錄頁(yè)處理,防止已登錄用戶(hù)重復(fù)訪問(wèn)登錄頁(yè);動(dòng)態(tài)路由注入。
使用router.addRoute()注入路由;路由跳轉(zhuǎn)處理,清除舊路由(避免重復(fù));
// 路由守衛(wèi)修改部分(router/index.ts)
router.beforeEach(async (to, from, next) => {
const store = loginStore()
const isLogin = !!store.id
// 未登錄狀態(tài)處理
if (!isLogin) {
return to.path === '/' ? next() : next('/')
}
// 已登錄但訪問(wèn)登錄頁(yè)時(shí)重定向
if (to.path === '/') {
return next('/home')
}
// 動(dòng)態(tài)路由加載邏輯
if (!store.routesLoaded) {
try {
// 直接從store獲取已保存的角色信息
const userRoles = store.roles
console.log(userRoles);
// 如果角色信息不存在則拋出錯(cuò)誤
if (!userRoles || userRoles.length === 0) {
throw new Error('用戶(hù)角色信息未獲取')
}
// 添加動(dòng)態(tài)路由
addDynamicRoutes(userRoles)
// 在添加路由后打印
console.log('當(dāng)前所有路由:', router.getRoutes().map(r => r.path))
// 更新加載狀態(tài)
store.setRoutesLoaded(true)
// 使用replace方式跳轉(zhuǎn)避免重復(fù)記錄歷史
return next({ ...to, replace: true })
} catch (error) {
console.error('路由加載失敗:', error)
// 清除用戶(hù)狀態(tài)并跳轉(zhuǎn)登錄頁(yè)
store.$reset()
return next('/')
}
}
next()
})最后,總結(jié)整個(gè)流程,強(qiáng)調(diào)關(guān)鍵點(diǎn),幫助用戶(hù)全面理解路由守衛(wèi)的工作機(jī)制和實(shí)現(xiàn)動(dòng)態(tài)路由加載的正確方法。
到此這篇關(guān)于vue實(shí)現(xiàn)前端控制動(dòng)態(tài)路由的示例代碼的文章就介紹到這了,更多相關(guān)vue 動(dòng)態(tài)路由內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3?響應(yīng)式高階用法之customRef()的使用
customRef()是Vue3的高級(jí)工具,允許開(kāi)發(fā)者創(chuàng)建具有復(fù)雜依賴(lài)跟蹤和自定義更新邏輯的ref對(duì)象,本文詳細(xì)介紹了customRef()的使用場(chǎng)景、基本用法、功能詳解以及最佳實(shí)踐,包括防抖、異步更新等用例,旨在幫助開(kāi)發(fā)者更好地理解和使用這一強(qiáng)大功能2024-09-09
詳解iview的checkbox多選框全選時(shí)校驗(yàn)問(wèn)題
這篇文章主要介紹了詳解iview的checkbox多選框全選時(shí)校驗(yàn)問(wèn)題,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-06-06
使用echarts柱狀圖實(shí)現(xiàn)select下拉刷新數(shù)據(jù)
這篇文章主要介紹了使用echarts柱狀圖實(shí)現(xiàn)select下拉刷新數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
Vue3?源碼分析reactive?readonly實(shí)例
這篇文章主要為大家介紹了Vue3?源碼分析reactive?readonly實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
基于Vue3實(shí)現(xiàn)掃碼槍掃碼并生成二維碼實(shí)例代碼
vue3生成二維碼的方式有很多種,下面這篇文章主要給大家介紹了關(guān)于如何基于Vue3實(shí)現(xiàn)掃碼槍掃碼并生成二維碼的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06
vue如何修改data中數(shù)據(jù)問(wèn)題
這篇文章主要介紹了vue如何修改data中數(shù)據(jù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Vue打包為相對(duì)路徑的具體實(shí)現(xiàn)方法
在Vue.js項(xiàng)目中,構(gòu)建后的資源文件(如CSS、JavaScript文件、圖片等)通常會(huì)被放置在指定的目錄下,為了確保這些文件能夠被正確加載,Vue CLI 提供了配置選項(xiàng)來(lái)指定這些文件的路徑,本文給大家介紹了Vue打包為相對(duì)路徑的具體實(shí)現(xiàn)方法,需要的朋友可以參考下2024-09-09

