menu.ts 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { shallowRef } from 'vue'
  2. import { AuthType } from '@/constants/menu'
  3. import { queryAccountMenu } from '@/services/api/account'
  4. import { defineStore } from '../store'
  5. import { sessionData } from '../storage'
  6. import { i18n } from "./language";
  7. export const useMenuStore = defineStore(() => {
  8. const loading = shallowRef(false)
  9. const userRoutes = sessionData.getRef('userRoutes')
  10. // 获取用户路由表
  11. const getUserRoutes = async () => {
  12. try {
  13. loading.value = true
  14. const res = await queryAccountMenu()
  15. const loop=(data: Model.UserRoutes[])=>{
  16. return data.reduce<Model.UserRoutes[]>((pre, cur) => {
  17. pre.push({
  18. ...cur,
  19. title: i18n.global.t(cur.title),
  20. children: cur.children ? loop(cur.children) : [],
  21. })
  22. return pre
  23. }, [])
  24. }
  25. userRoutes.value = loop(res)
  26. } finally {
  27. loading.value = false
  28. }
  29. }
  30. // 根据 code 查找对应的子路由
  31. const getChildrenRoutes = (routeName: string) => {
  32. const findChildren = (data: Model.UserRoutes[]): Model.UserRoutes[] => {
  33. for (const item of data) {
  34. const { code, children } = item
  35. if (code === routeName) return children ?? []
  36. if (children) {
  37. const res = findChildren(children)
  38. if (res.length) return res
  39. }
  40. }
  41. return []
  42. }
  43. return findChildren(userRoutes.value)
  44. }
  45. // 过滤菜单
  46. const filterMenus = (data: Model.UserRoutes[], parentPath = '') => {
  47. return data.reduce<Model.UserRoutes[]>((pre, cur) => {
  48. if (!cur.hidden && cur.authType === AuthType.Menu) {
  49. const routePath = (parentPath ? parentPath + '/' : '') + cur.url
  50. pre.push({
  51. ...cur,
  52. url: routePath,
  53. children: cur.children ? filterMenus(cur.children, routePath) : [],
  54. })
  55. }
  56. return pre
  57. }, [])
  58. }
  59. // 获取用户菜单(无限级)
  60. const getUserMenus = (level = 0) => {
  61. // 过滤层级
  62. const filterLevel = (data: Model.UserRoutes[], n: number): Model.UserRoutes[] => {
  63. if (level) {
  64. return data.map((e) => ({ ...e, children: n <= 1 ? [] : filterLevel(e.children ?? [], n - 1) }))
  65. }
  66. return data
  67. }
  68. return filterMenus(filterLevel(userRoutes.value, level))
  69. }
  70. // 获取子菜单
  71. const getChildrenMenus = (routeName: string) => {
  72. const children = getChildrenRoutes(routeName)
  73. return filterMenus(children)
  74. }
  75. return {
  76. loading,
  77. userRoutes,
  78. getUserRoutes,
  79. getChildrenRoutes,
  80. getUserMenus,
  81. getChildrenMenus
  82. }
  83. })