permission.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 { appStore } from '/@/store/modules/app';
  8. import { usePermission } from '/@/hooks/web/usePermission';
  9. import { PermissionModeEnum } from '/@/enums/appEnum';
  10. const { hasPermission } = usePermission();
  11. function isAuth(el: Element, binding: any) {
  12. const value = binding.value;
  13. if (!value) return;
  14. if (!hasPermission(value)) {
  15. if (el.parentNode) {
  16. el.parentNode.removeChild(el);
  17. }
  18. }
  19. }
  20. function isBackMode() {
  21. return appStore.getProjectConfig.permissionMode === PermissionModeEnum.BACK;
  22. }
  23. const mounted = (el: Element, binding: DirectiveBinding<any>) => {
  24. if (isBackMode()) return;
  25. isAuth(el, binding);
  26. };
  27. const updated = (el: Element, binding: DirectiveBinding<any>) => {
  28. if (!isBackMode()) return;
  29. isAuth(el, binding);
  30. };
  31. const authDirective: Directive = {
  32. mounted,
  33. updated,
  34. };
  35. export function setupPermissionDirective(app: App) {
  36. app.directive('auth', authDirective);
  37. }
  38. export default authDirective;