hasRole.ts 792 B

123456789101112131415161718192021222324252627
  1. import type { App } from 'vue'
  2. import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
  3. import { useI18n } from '@/hooks/web/useI18n'
  4. const { t } = useI18n() // 国际化
  5. export function hasRole(app: App<Element>) {
  6. app.directive('hasRole', (el, binding) => {
  7. const { wsCache } = useCache()
  8. const { value } = binding
  9. const super_admin = 'admin'
  10. const roles = wsCache.get(CACHE_KEY.USER).roles
  11. if (value && value instanceof Array && value.length > 0) {
  12. const roleFlag = value
  13. const hasRole = roles.some((role: string) => {
  14. return super_admin === role || roleFlag.includes(role)
  15. })
  16. if (!hasRole) {
  17. el.parentNode && el.parentNode.removeChild(el)
  18. }
  19. } else {
  20. throw new Error(t('permission.hasRole'))
  21. }
  22. })
  23. }