admin-vben5/packages/effects/access/src/directive.ts
handsomeFu 8adb22847d
perf: optimize the access directive to support string passing (#4246)
* perf: 优化access指令用法并改进参数类型

重构access权限指令以接受角色和代码形式的权限检查。通过支持数组和字符串作为指令值来简化用法,从而提高灵活性。此外,改进指令绑定类型定义以提升类型安全性。

* docs: 更新中英文文档示例以支持字符串权限码绑定更新了中文和英文文档中的示例
2024-08-27 11:17:04 +08:00

43 lines
1.0 KiB
TypeScript

/**
* Global authority directive
* Used for fine-grained control of component permissions
* @Example v-access:role="[ROLE_NAME]" or v-access:role="ROLE_NAME"
* @Example v-access:code="[ROLE_CODE]" or v-access:code="ROLE_CODE"
*/
import type { App, Directive, DirectiveBinding } from 'vue';
import { useAccess } from './use-access';
function isAccessible(
el: Element,
binding: DirectiveBinding<string | string[]>,
) {
const { accessMode, hasAccessByCodes, hasAccessByRoles } = useAccess();
const value = binding.value;
if (!value) return;
const authMethod =
accessMode.value === 'frontend' && binding.arg === 'role'
? hasAccessByRoles
: hasAccessByCodes;
const values = Array.isArray(value) ? value : [value];
if (!authMethod(values)) {
el?.remove();
}
}
const mounted = (el: Element, binding: DirectiveBinding<string | string[]>) => {
isAccessible(el, binding);
};
const authDirective: Directive = {
mounted,
};
export function registerAccessDirective(app: App) {
app.directive('access', authDirective);
}