index.jsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { computed, defineComponent, inject, provide, reactive } from 'vue'
  2. import { isInputEmpty } from '@cip/utils/util'
  3. const ownPrivilegesKey = Symbol('ownPrivileges')
  4. // 收集依赖用于下级的授权
  5. export const useCollectPrivileges = (value) => {
  6. provide(ownPrivilegesKey, reactive({ value }))
  7. }
  8. export const usePrivileges = () => {
  9. return inject(ownPrivilegesKey, { value: [] })
  10. }
  11. export default defineComponent({
  12. name: 'CipJudgePrivilege',
  13. props: {
  14. privilege: [Object, String, Number] // 不支持
  15. },
  16. setup (props, { slots }) {
  17. const ownPrivileges = usePrivileges() // 当前拥有的权限 由provide下发
  18. const judgeType = computed(() => {
  19. if (typeof props.privilege === 'object' && props.privilege.type === 'and') {
  20. return 'and'
  21. }
  22. return 'or'
  23. })
  24. // 返回数组
  25. const privilegeValues = computed(() => {
  26. let codes = []
  27. if (typeof props.privilege === 'object') { // 判断是否为对象
  28. codes = codes.concat(props.privilege.code)
  29. } else {
  30. codes = codes.concat(props.privilege)
  31. }
  32. return codes
  33. })
  34. // 判断是否拥有特权
  35. const hasPrivilege = computed(() => {
  36. if (judgeType.value === 'or') { // 或模式 存在 '' | undefined | null
  37. if (privilegeValues.value.findIndex(v => isInputEmpty(v)) > -1) return true
  38. }
  39. // 过滤掉 '' | undefined | null
  40. const effectiveCodes = privilegeValues.value.filter(code => !isInputEmpty(code))
  41. if (effectiveCodes.length === 0) return true
  42. if (judgeType.value === 'and') {
  43. return !effectiveCodes.some(v => !ownPrivileges.value.includes(v))
  44. } else {
  45. return effectiveCodes.some(v => ownPrivileges.value.includes(v))
  46. }
  47. })
  48. return () => {
  49. if (!hasPrivilege.value) {
  50. // 渲染无权限插槽
  51. return slots.noPrivilege?.()
  52. } else {
  53. // 渲染默认插槽
  54. return slots.default?.()
  55. }
  56. }
  57. }
  58. })