hasPermi.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import type { App, Directive, DirectiveBinding } from 'vue'
  2. import { useI18n } from '@/hooks/web/useI18n'
  3. import { useCache } from '@/hooks/web/useCache'
  4. import { intersection } from 'lodash-es'
  5. import { isArray } from '@/utils/is'
  6. import { useAppStoreWithOut } from '@/store/modules/app'
  7. const { t } = useI18n()
  8. const { wsCache } = useCache()
  9. const appStore = useAppStoreWithOut()
  10. // 全部权限
  11. const all_permission = ['*.*.*']
  12. const hasPermission = (value: string | string[]): boolean => {
  13. const permissions = wsCache.get(appStore.getUserInfo).permissions as string[]
  14. if (!value) {
  15. throw new Error(t('permission.hasPermission'))
  16. }
  17. if (!isArray(value)) {
  18. return permissions?.includes(value as string)
  19. }
  20. if (all_permission[0] === permissions[0]) {
  21. return true
  22. }
  23. return (intersection(value, permissions) as string[]).length > 0
  24. }
  25. function hasPermi(el: Element, binding: DirectiveBinding) {
  26. const value = binding.value
  27. const flag = hasPermission(value)
  28. if (!flag) {
  29. el.parentNode?.removeChild(el)
  30. }
  31. }
  32. const mounted = (el: Element, binding: DirectiveBinding<any>) => {
  33. hasPermi(el, binding)
  34. }
  35. const permiDirective: Directive = {
  36. mounted
  37. }
  38. export const setupPermissionDirective = (app: App<Element>) => {
  39. app.directive('hasPermi', permiDirective)
  40. }
  41. export default permiDirective