index.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { createRouter, createWebHistory } from "vue-router";
  2. import guard from "./guard";
  3. // 导入views文件夹下的所有组件
  4. const modules = import.meta.glob("../views/**/index.vue");
  5. // 匹配到的文件名数组
  6. let aotuRoutes: any[] = [];
  7. //根据名字查找路由项目
  8. const aotuRoutesFind = (name: String) => {
  9. let list: any = [];
  10. //递归查询所有路由,子路由;添加至list
  11. const recursionPush = (routes: any) => {
  12. routes.forEach((item: any) => {
  13. list.push(item);
  14. recursionPush(item.children);
  15. });
  16. };
  17. recursionPush(aotuRoutes);
  18. //返回查找到的路由
  19. return list.find((route: any) => route.name == name);
  20. };
  21. for (const path in modules) {
  22. //提取路由信息
  23. let nameArr = path.split("/");
  24. //子路由循环时有作用
  25. let aotuRoutesItem = aotuRoutes;
  26. //子路由层次标识
  27. let index = 0;
  28. //判断是否是子路由
  29. for (let i = 0; i < nameArr.length - 4; i = i + 2) {
  30. aotuRoutesItem = aotuRoutesItem.find(
  31. (route: any) => route.name == nameArr[i + 2]
  32. ).children;
  33. index++;
  34. }
  35. //路径生成
  36. let routePath = "";
  37. for (let i = 0; i <= index; i++) {
  38. routePath += "/" + nameArr[i * 2 + 2];
  39. }
  40. //设置文件夹名带有-default的子路由为默认路由
  41. if (nameArr[index * 2 + 2].includes("-default")) {
  42. aotuRoutesFind(nameArr[index * 2]).redirect = routePath;
  43. }
  44. //添加路由信息
  45. aotuRoutesItem.push({
  46. name: nameArr[index * 2 + 2],
  47. path: routePath,
  48. component: modules[path],
  49. children: [],
  50. });
  51. }
  52. // 创建路由实例并传递 `routes` 配置
  53. const router = createRouter({
  54. history: createWebHistory(),
  55. routes: [
  56. {
  57. path: "/",
  58. redirect: "/home/test",
  59. },
  60. ...aotuRoutes,
  61. ],
  62. });
  63. //注入路由守卫
  64. guard(router);
  65. export default router;