util.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. function buildMenu(menu, menuList, menuIds) {
  2. let nextLayer = []
  3. for (let i = menu.length - 1; i > -1; i--) {
  4. const currentMenu = menu[i]
  5. const subMenu = menuList.filter(item => {
  6. if (item.parent_id === currentMenu.menu_id) {
  7. menuIds.push(item.menu_id)
  8. return true
  9. }
  10. })
  11. nextLayer = nextLayer.concat(subMenu)
  12. currentMenu.children = subMenu
  13. }
  14. if (nextLayer.length) {
  15. buildMenu(nextLayer, menuList, menuIds)
  16. }
  17. }
  18. function getParentIds(menuItem, menuList) {
  19. const parentArr = []
  20. let currentItem = menuItem
  21. while (currentItem && currentItem.parent_id) {
  22. parentArr.push(currentItem.parent_id)
  23. currentItem = menuList.find(item => item.menu_id === currentItem.parent_id)
  24. }
  25. return parentArr
  26. }
  27. function buildMenus(menuList, trim = true) {
  28. // 保证父子级顺序
  29. menuList = menuList.sort(function(a, b) {
  30. const parentIdsA = getParentIds(a, menuList)
  31. const parentIdsB = getParentIds(b, menuList)
  32. if (parentIdsA.includes(b.menu_id)) {
  33. return 1
  34. }
  35. return parentIdsA.length - parentIdsB.length || a.sort - b.sort
  36. })
  37. // 删除无subMenu且非子节点的菜单项
  38. if (trim) {
  39. for (let i = menuList.length - 1; i > -1; i--) {
  40. const currentMenu = menuList[i]
  41. const subMenu = menuList.filter(subMenuItem => subMenuItem.parent_id === currentMenu.menu_id)
  42. if (!currentMenu.isLeafNode && !subMenu.length) {
  43. menuList.splice(i, 1)
  44. }
  45. }
  46. }
  47. const menuIds = []
  48. const menu = menuList.filter(item => {
  49. if (!item.parent_id) {
  50. menuIds.push(item.menu_id)
  51. return true
  52. }
  53. })
  54. buildMenu(menu, menuList, menuIds)
  55. // 包含所有无效菜单
  56. if (!trim && menuIds.length !== menuList.length) {
  57. menu.push(...menuList.filter(item => !menuIds.includes(item.menu_id)))
  58. }
  59. return menu
  60. }
  61. export {
  62. buildMenu,
  63. buildMenus
  64. }