admin-vben5/packages/utils/src/helpers/generate-routes-frontend.ts
Vben 524b9badf2
feat: add VbenForm component (#4352)
* feat: add form component

* fix: build error

* feat: add form adapter

* feat: add some component

* feat: add some component

* feat: add example

* feat: suppoer custom action button

* chore: update

* feat: add example

* feat: add formModel,formDrawer demo

* fix: build error

* fix: typo

* fix: ci error

---------

Co-authored-by: jinmao <jinmao88@qq.com>
Co-authored-by: likui628 <90845831+likui628@users.noreply.github.com>
2024-09-10 21:48:51 +08:00

59 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { RouteRecordRaw } from 'vue-router';
import { filterTree, mapTree } from '@vben-core/shared/utils';
/**
* 动态生成路由 - 前端方式
*/
async function generateRoutesByFrontend(
routes: RouteRecordRaw[],
roles: string[],
forbiddenComponent?: RouteRecordRaw['component'],
): Promise<RouteRecordRaw[]> {
// 根据角色标识过滤路由表,判断当前用户是否拥有指定权限
const finalRoutes = filterTree(routes, (route) => {
return hasAuthority(route, roles);
});
if (!forbiddenComponent) {
return finalRoutes;
}
// 如果有禁止访问的页面将禁止访问的页面替换为403页面
return mapTree(finalRoutes, (route) => {
if (menuHasVisibleWithForbidden(route)) {
route.component = forbiddenComponent;
}
return route;
});
}
/**
* 判断路由是否有权限访问
* @param route
* @param access
*/
function hasAuthority(route: RouteRecordRaw, access: string[]) {
const authority = route.meta?.authority;
if (!authority) {
return true;
}
const canAccess = access.some((value) => authority.includes(value));
return canAccess || (!canAccess && menuHasVisibleWithForbidden(route));
}
/**
* 判断路由是否在菜单中显示但是访问会被重定向到403
* @param route
*/
function menuHasVisibleWithForbidden(route: RouteRecordRaw) {
return (
!!route.meta?.authority &&
Reflect.has(route.meta || {}, 'menuVisibleWithForbidden') &&
!!route.meta?.menuVisibleWithForbidden
);
}
export { generateRoutesByFrontend, hasAuthority };