自动生成路由
基础环境
vue 3.4
ts 5.5
vite 5.4
自动生成路由
只有一个基础的路由页面,根据菜单自动生成路由,不适用于所有的项目,可自行玩玩
1.文件目录结构
└── src/
├── assets/
├── layouts/
├── admin.vue // admin 一级路由
├── member.vue // member 一级路由
├── router/
│ ├── aotoload.ts //自动生成路由函数
│ └── index.ts //路由基础文件
├── store/
├── utils/
├── views/
├── admin/
├── role.vue //admin 二级路由
├── user.vue //admin 二级路由
└── member/
├── aaa.vue //member 二级路由
├── App.vue
└── main.ts
├── index.html
├── tsconfig.json
├── vite.config.ts
└── package.json
2./src/router/index.ts
import { App } from 'vue';
import { createRouter, createWebHashHistory } from 'vue-router';
import layoutRouters from './autoload';
const routers = createRouter({
history: createWebHashHistory(),
routes: [ ...layoutRouters]
});
export function setupRouter(app: App) {
app.use(routers);
}
3./src/router/aotoload.ts
import { RouteRecordRaw } from 'vue-router';
type G = { [key: string]: any };
const layouts = import.meta.glob<G>('../layouts/*.vue');
const views = import.meta.glob<G>('../views/**/*.vue');
function getRouters() {
const layoutRouters = [] as RouteRecordRaw[];
Object.entries(layouts).forEach(([file, module]) => {
const route = getRouterByModule(file, module);
route.children = getChildrenRouterByModule(route);
layoutRouters.push(route);
});
return layoutRouters;
}
function getRouterByModule(file: string, module: G) {
const name = file.replace(/.+layouts\/|.+views\/|\.vue/gi, '');
const router = {
name: name.replace('/', '.'),
path: '/' + name,
component: module
} as RouteRecordRaw;
return router;
}
function getChildrenRouterByModule(layoutRouter: RouteRecordRaw) {
const route = [] as RouteRecordRaw[];
Object.entries(views).forEach(([file, module]) => {
if (file.includes(`../views/${layoutRouter.name as string}`)) {
const router = getRouterByModule(file, module);
route.push(router);
}
});
return route;
}
export default getRouters();
4.一级路由
/src/layouts/admin.vue
<template>
<div>admin <RouterView></RouterView></div>
</template>
/src/layouts/member.vue
<template>
<div>admin <RouterView></RouterView></div>
</template>
4.效果