1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| const LayoutPage = "Layout";
const modules = import.meta.glob("@/views/pages/**/*.vue");
const staticRoutes = [ { path: "/", redirect: "/dashboard" }, { path: "/login", meta: { title: "登录" }, component: () => import("@/views/Login.vue"), }, { path: "/", name: LayoutPage, component: () => import(`@/views/${LayoutPage}.vue`), }, { path: "/:pathMatch(.*)*", meta: { title: "404" }, component: () => import("@/views/404.vue"), }, ];
const router = createRouter({ history: createWebHistory(), routes: staticRoutes, });
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
document.title = `${to.meta.title} | Demo`;
if (getLocal("token")) {
if (to.path == "/login") { next(); } else { const menusStorage = getLocal("menus") || [];
if (menusStorage.length > 0) { if (router.getRoutes().length == staticRoutes.length) { mergeRoutes(menusStorage, router); next({ ...to, replace: true }); } else { next(); } } else {
const menusData = mockData; setLocal("menus", menusData); if (menusData.length > 0) { mergeRoutes(menusData, router); next({ ...to, replace: true }); } else { throw new Error("菜单列表为空"); }
}
}
} else {
if (to.path == "/login") { next(); } else { next("/login"); }
}
});
export const iterateMenu = (data: any) => { let result: any = [];
data.forEach((item: any, index: number) => { result.push({ path: item.menuUrl, meta: { title: item.name, icon: item.icon }, component: modules[`/src/views/pages${uriToFileName(item.menuUrl)}.vue`], });
if (item.children.length > 0) result[index].children = iterateMenu(item.children); });
return result; };
export const uriToFileName = (uri: string) => { let strList = uri.split("/"); let fileName = strList[strList.length - 1]; let prefix = uri.replace(fileName, ""); return `${prefix + fileName[0]?.toUpperCase() + fileName?.slice(1)}`; };
export const mergeRoutes = (menus: any, router: any) => { const dynamicMenu = iterateMenu(menus);
dynamicMenu.forEach((item: any) => router.addRoute("Layout", item));
}
|