路由权限添加
This commit is contained in:
@@ -11,6 +11,7 @@ import { ROOT_ROUTE } from '@/router/routes/builtin';
|
||||
import { getRouteName, getRoutePath } from '@/router/elegant/transform';
|
||||
import { useAuthStore } from '../auth';
|
||||
import { useTabStore } from '../tab';
|
||||
import { localStg } from '@/utils/storage';
|
||||
import {
|
||||
filterAuthRoutesByRoles,
|
||||
getBreadcrumbsByRoute,
|
||||
@@ -190,14 +191,52 @@ export const useRouteStore = defineStore(SetupStoreId.Route, () => {
|
||||
tabStore.initHomeTab();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据允许的路径列表,过滤路由树
|
||||
* @param {Array} routes - 路由对象数组(可嵌套 children)
|
||||
* @param {Array} allowedPaths - 允许的路径字符串数组
|
||||
* @param {string} parentPath - 父级路径(用于拼接相对路径,本例中所有路径都是绝对路径,可忽略)
|
||||
* @returns {Array} 过滤后的路由数组
|
||||
*/
|
||||
function filterRoutesByPaths(routes: ElegantConstRoute[], allowedPaths: string[], parentPath = '') {
|
||||
const result = [];
|
||||
const pathSet = new Set(allowedPaths);
|
||||
|
||||
for (const route of routes) {
|
||||
// 计算完整路径(如果路径以 '/' 开头则为绝对路径,否则拼接父路径)
|
||||
const fullPath = route.path.startsWith('/')
|
||||
? route.path
|
||||
: `${parentPath}/${route.path}`.replace(/\/+/g, '/');
|
||||
|
||||
// 检查当前路由是否在允许列表中
|
||||
const isAllowed = pathSet.has(fullPath);
|
||||
|
||||
// 递归处理子路由
|
||||
let filteredChildren = [];
|
||||
if (route.children && route.children.length) {
|
||||
filteredChildren = filterRoutesByPaths(route.children, allowedPaths, fullPath);
|
||||
}
|
||||
|
||||
// 只要当前路由匹配,或有子路由匹配,则保留该路由
|
||||
if (isAllowed || filteredChildren.length > 0) {
|
||||
result.push({
|
||||
...route,
|
||||
path: fullPath, // 使用完整路径(可确保路径一致性)
|
||||
children: filteredChildren.length ? filteredChildren : route.children
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
/** Init static auth route */
|
||||
function initStaticAuthRoute() {
|
||||
const { authRoutes: staticAuthRoutes } = createStaticRoutes();
|
||||
|
||||
const filteredRoutes = filterRoutesByPaths(staticAuthRoutes, localStg.get('userInfo').perms);
|
||||
if (authStore.isStaticSuper) {
|
||||
addAuthRoutes(staticAuthRoutes);
|
||||
addAuthRoutes(filteredRoutes);
|
||||
} else {
|
||||
const filteredAuthRoutes = filterAuthRoutesByRoles(staticAuthRoutes, authStore.userInfo.roles);
|
||||
const filteredAuthRoutes = filterAuthRoutesByRoles(filteredRoutes, authStore.userInfo.roles);
|
||||
|
||||
addAuthRoutes(filteredAuthRoutes);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user