1、使用 import.meta.glob
加载所有vue文件
const modules = import.meta.glob("../views/**/*.vue");
let autoRoutes: Route[] = [];
for (let key in modules) {
console.log(key);
autoRoutes.push({
filePath: key,
path: key.replace("../views/", "/").replace(".vue", ""),
component: modules[key]
});
}
2、使用addRoute
挂载动态路由
const mountRoutes = async () => {
for (const item of autoRoutes) {
if (item.path) {
const route = {
path: item.path,
component: () => import(item.filePath)
};
console.log(route);
router.addRoute(route);
}
}
};
3、路由配置
import { createRouter, createWebHashHistory } from "vue-router";
import indexPage from "../views/index/index.vue";
import { mountRoutes } from "./auto-load";
import { getToken } from "../utils/token";
const routes = [
{ path: "/", component: indexPage },
{ path: "/login", component: () => import("../views-common/account/login/index.vue") }
];
export const router = createRouter({
history: createWebHashHistory(),
routes
});
const authWhiteList = [
"/login"
];
// 是否已经挂载动态路由标识
let routeHasMounted = false;
router.beforeEach(async (to, from, next) => {
// 是否为免登录白名单 是的话直接放行
if (authWhiteList.includes(to.path)) {
next();
} else {
// 需要免登录的页面 判断是否已经登录
if (!getToken()) {
// 未登录的直接跳转到登录页面
next({ path: "/login", replace: true });
} else {
// 已经登录的 判断是否挂载动态路由
if (!routeHasMounted) {
// 未挂载状态 挂载动态路由
await mountRoutes();
// 将挂载状态设置为true
routeHasMounted = true;
// 重新路由到当前页面 因为此页面在第一次打开的时候是 匹配不到路由的
// 这里replace: true 是为了让网页不能返回上一页
next({ ...to, replace: true });
} else {
// 已经挂载状态 直接放行
next();
}
}
}
});