dynamicRouter.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { RouteRecordRaw } from 'vue-router'
  2. import { AuthType } from '@/constants/menu'
  3. import { useMenuStore } from '@/stores'
  4. import router from '../router'
  5. export default new (class {
  6. /** 防止动态路由无限加载 */
  7. isReady = false;
  8. /**
  9. * 添加404页面
  10. */
  11. private addNotFound() {
  12. router.addRoute({
  13. path: '/:pathMatch(.*)*',
  14. name: 'Error',
  15. component: () => import('../views/error/404.vue'),
  16. })
  17. }
  18. /**
  19. * 动态添加路由
  20. * @param routes
  21. * @param parentName
  22. */
  23. private addRoutes(routes: Ermcp.UserMenu[], parentName = '') {
  24. routes.forEach((item) => {
  25. if (item.authType === AuthType.Menu && item.component) {
  26. let component;
  27. switch (item.component) {
  28. case 'Page': {
  29. component = () => import('../components/layouts/page/index.vue');
  30. break;
  31. }
  32. case 'Main': {
  33. component = () => import('../components/layouts/main/index.vue');
  34. break;
  35. }
  36. default: {
  37. const componentString = item.component.replace(/^\/+/, ''); // 过滤字符串前面所有 '/' 字符
  38. const componentPath = componentString.replace(/\.\w+$/, ''); // 过滤后缀名,为了让 import 加入 .vue ,不然会有警告提示...
  39. component = () => import('../' + componentPath + '.vue');
  40. }
  41. }
  42. const route: RouteRecordRaw = {
  43. path: item.url,
  44. name: item.code,
  45. component,
  46. meta: {
  47. title: item.title,
  48. icon: item.icon,
  49. remark: item.remark,
  50. },
  51. }
  52. parentName ? router.addRoute(parentName, route) : router.addRoute(route);
  53. if (item.children && item.children.length) {
  54. this.addRoutes(item.children, item.code);
  55. }
  56. }
  57. })
  58. }
  59. /**
  60. * 注册路由
  61. * @returns
  62. */
  63. registerRoutes() {
  64. const { userMenus } = useMenuStore();
  65. this.addNotFound();
  66. this.addRoutes(userMenus.value);
  67. this.isReady = true;
  68. }
  69. })