util.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { isArray, isInputEmpty } from '@cip/utils/util'
  2. import { isHideInMenu } from '@cip/components/main/helper'
  3. export const getFirstMenuItem = (subMenu) => {
  4. if (subMenu?.children && subMenu.children.length > 0) {
  5. return getFirstMenuItem(subMenu.children[0])
  6. }
  7. return subMenu
  8. }
  9. // 判断权限
  10. const hasPrivilege = (item, privileges) => {
  11. const code = item.code || item.meta?.code
  12. if (isInputEmpty(code)) return true // 没有code即表示此不需要权限
  13. if (isArray(code)) {
  14. // code为数组的情况
  15. if (code.length === 0) return true // 空数组代表不需要权限
  16. return code.some(v => {
  17. if (isInputEmpty(v)) return true // 没有code即表示此不需要权限
  18. return privileges?.includes(v)
  19. })
  20. } else {
  21. return privileges?.includes(code)
  22. }
  23. }
  24. const mapFilter = (list, mCb, fcb) => {
  25. return list.map(mCb).filter(fcb)
  26. }
  27. export const filterMenu = (menu = [], privileges) => {
  28. return mapFilter(menu, child => {
  29. if (!isHideInMenu(child) && hasPrivilege(child, privileges)) {
  30. if (child.children) {
  31. return Object.assign({}, child, { children: filterMenu(child.children, privileges) })
  32. } else {
  33. return Object.assign({}, child)
  34. }
  35. }
  36. // 无权限会返回 undefined
  37. }, v => { return v !== undefined && !((v?.name || '').indexOf('_') === 0 && (v.children || []).length === 0) })
  38. }
  39. export const findMenu = (menu, name) => {
  40. return menu.find(menu => menu.name === name)
  41. }
  42. /**
  43. * 根据匹配到的菜单路径获取选中的菜单
  44. * @param menuPath
  45. * @returns {String}
  46. */
  47. export const getActiveNameByMatchedMenu = (menuPath) => {
  48. if (!menuPath || menuPath.length === 0) return ''
  49. for (let i = 0; i < menuPath.length; i++) {
  50. const menu = menuPath[menuPath.length - 1 - i]
  51. if (!isHideInMenu(menu)) {
  52. return menu.name // 跳出循环
  53. }
  54. }
  55. return '' // 最后的保险
  56. }