index.jsx 1.7 KB

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