permission.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /**
  2. * 按钮级权限控制
  3. */
  4. import store from '@/store';
  5. /* 数组是否有某些值 */
  6. const arrayHas = function (array, value) {
  7. if (!value) {
  8. return true;
  9. }
  10. if (!array) {
  11. return false;
  12. }
  13. if (Array.isArray(value)) {
  14. for (let i = 0; i < value.length; i++) {
  15. if (array.indexOf(value[i]) === -1) {
  16. return false;
  17. }
  18. }
  19. return true;
  20. }
  21. return array.indexOf(value) !== -1;
  22. };
  23. /* 数组是否有任意值 */
  24. const arrayHasAny = function (array, value) {
  25. if (!value) {
  26. return true;
  27. }
  28. if (!array) {
  29. return false;
  30. }
  31. if (Array.isArray(value)) {
  32. for (let i = 0; i < value.length; i++) {
  33. if (array.indexOf(value[i]) !== -1) {
  34. return true;
  35. }
  36. }
  37. return false;
  38. }
  39. return array.indexOf(value) !== -1;
  40. };
  41. /**
  42. * 是否有某些角色
  43. * @param value 角色字符或字符数组
  44. */
  45. export function hasRole(value) {
  46. return arrayHas(store.state.user?.roles, value);
  47. }
  48. /**
  49. * 是否有任意角色
  50. * @param value 角色字符或字符数组
  51. */
  52. export function hasAnyRole(value) {
  53. return arrayHasAny(store.state.user?.roles, value);
  54. }
  55. /**
  56. * 是否有某些权限
  57. * @param value 权限字符或字符数组
  58. */
  59. export function hasPermission(value) {
  60. return arrayHas(store.state.user?.authorities, value);
  61. }
  62. /**
  63. * 是否有任意权限
  64. * @param value 权限字符或字符数组
  65. */
  66. export function hasAnyPermission(value) {
  67. return arrayHasAny(store.state.user?.authorities, value);
  68. }
  69. export default {
  70. install(Vue) {
  71. // 添加全局方法
  72. Vue.prototype.$hasRole = hasRole;
  73. Vue.prototype.$hasAnyRole = hasAnyRole;
  74. Vue.prototype.$hasPermission = hasPermission;
  75. Vue.prototype.$hasAnyPermission = hasAnyPermission;
  76. // 添加自定义指令
  77. Vue.directive('role', {
  78. inserted: (el, binding) => {
  79. if (!hasRole(binding.value)) {
  80. el.parentNode && el.parentNode.removeChild(el);
  81. }
  82. }
  83. });
  84. Vue.directive('any-role', {
  85. inserted: (el, binding) => {
  86. if (!hasAnyRole(binding.value)) {
  87. el.parentNode && el.parentNode.removeChild(el);
  88. }
  89. }
  90. });
  91. Vue.directive('permission', {
  92. inserted: (el, binding) => {
  93. if (!hasPermission(binding.value)) {
  94. el.parentNode && el.parentNode.removeChild(el);
  95. }
  96. }
  97. });
  98. Vue.directive('any-permission', {
  99. inserted: (el, binding) => {
  100. if (!hasAnyPermission(binding.value)) {
  101. el.parentNode && el.parentNode.removeChild(el);
  102. }
  103. }
  104. });
  105. }
  106. };