utils.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * 通过menus 计算出asyncRoutes 动态路由
  3. */
  4. import { RouteRecordRaw } from "vue-router"
  5. import { asyncComponentsType } from "@/router/routers"
  6. export const generateAsyncMenusAsyncRoutes = (menus: menuType[], components: asyncComponentsType) => {
  7. return {
  8. asyncRoutes: generateAsyncRoutes(menus, components),
  9. asyncMenus: generateAsyncMenus(menus)
  10. }
  11. }
  12. export const generateAsyncRoutes = (menus: menuType[], components: asyncComponentsType) => {
  13. function menusAsyncRoutes(menus: menuType[]) {
  14. const layoutRoutes: RouteRecordRaw[] = []
  15. const singlepageRoutes: RouteRecordRaw[] = []
  16. for (const menu of menus) {
  17. const { path, component, meta } = menu
  18. if (menu.children && menu.children.length > 0) {
  19. const asyncRoutes = menusAsyncRoutes(menu.children)
  20. layoutRoutes.push(...asyncRoutes.layoutRoutes)
  21. singlepageRoutes.push(...asyncRoutes.singlepageRoutes)
  22. } else {
  23. ;(meta.routeType === "layout" ? layoutRoutes : singlepageRoutes).push({
  24. path: path,
  25. name: component,
  26. component: components[component],
  27. meta
  28. })
  29. }
  30. }
  31. return {
  32. layoutRoutes,
  33. singlepageRoutes
  34. }
  35. }
  36. const { layoutRoutes, singlepageRoutes } = menusAsyncRoutes(menus)
  37. const asyncRoutes: RouteRecordRaw[] = [
  38. {
  39. path: "/layout",
  40. name: "layout",
  41. redirect: "/noRedirect",
  42. component: components["layout"],
  43. children: layoutRoutes
  44. },
  45. ...singlepageRoutes
  46. ]
  47. //默认获取第一个菜单为首页
  48. function getHomePageMenus(menus: menuType[]): string {
  49. const menu = menus[0]
  50. if (!menu) {
  51. return "/noRedirect"
  52. } else if (menu.children && menu.children.length) {
  53. return getHomePageMenus(menu.children)
  54. } else {
  55. return menu.path
  56. }
  57. }
  58. const homePagePath = getHomePageMenus(menus)
  59. //添加首页
  60. asyncRoutes.push({
  61. path: "/",
  62. redirect: homePagePath
  63. })
  64. //添加 404
  65. asyncRoutes.push({
  66. path: "/:pathMatch(.*)*",
  67. name: "errorPage",
  68. component: () => import("@/viewsframe/errorPage")
  69. })
  70. return asyncRoutes
  71. }
  72. export const generateAsyncMenus = (menus: menuType[]) => {
  73. return filterMenus(menus)
  74. function filterMenus(menus: menuType[]) {
  75. return menus.filter(item => {
  76. if (item.children.length) {
  77. item.children = filterMenus(item.children)
  78. }
  79. return item.meta.routeType === "layout"
  80. })
  81. }
  82. }