permission.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * Global authority directive
  3. * Used for fine-grained control of component permissions
  4. * @Example v-auth="RoleEnum.TEST"
  5. */
  6. import type { App, Directive, DirectiveBinding } from 'vue';
  7. import projectSetting from '/@/settings/projectSetting';
  8. import { usePermission } from '/@/hooks/web/usePermission';
  9. import { PermissionModeEnum } from '/@/enums/appEnum';
  10. function isAuth(el: Element, binding: any) {
  11. const { hasPermission } = usePermission();
  12. const value = binding.value;
  13. if (!value) return;
  14. if (!hasPermission(value)) {
  15. el.parentNode?.removeChild(el);
  16. }
  17. }
  18. function isBackMode() {
  19. return projectSetting.permissionMode === PermissionModeEnum.BACK;
  20. }
  21. const mounted = (el: Element, binding: DirectiveBinding<any>) => {
  22. if (isBackMode()) return;
  23. isAuth(el, binding);
  24. };
  25. const updated = (el: Element, binding: DirectiveBinding<any>) => {
  26. if (!isBackMode()) return;
  27. isAuth(el, binding);
  28. };
  29. const authDirective: Directive = {
  30. mounted,
  31. updated,
  32. };
  33. export function setupPermissionDirective(app: App) {
  34. app.directive('auth', authDirective);
  35. }
  36. export default authDirective;