起因:
当项目过大时,路由越来越多时,免不了一个文件一个文件的手动引入,这样不仅繁琐,而且导致文件过大。
解决办法:使用路由自动化导入
目录结构图
views/xxx/page.ts
export default {
title: '首页',
menuShow: true,
menuSort: 1
}
router/index.ts
- webpack写法
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Layout from '../layout/index.vue'
// 使用webpack提供的api获取views下的所有文件信息
const reqRouter = require.context('@/views', true, /\page.ts$/)
const autoLoadRoutes: Array<RouteRecordRaw> = []
reqRouter.keys().forEach((key) => {
// 获取page.ts中的信息
let reqRouterDefault = reqRouter(key).default
let path = key.replace('./', '').replace('/page.ts', '')
autoLoadRoutes.push({
path: `/${path}`,
name: path,
meta: reqRouterDefault,
component: () => import(`@/views/${path}/index.vue`)
})
})
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'index',
redirect: '/home',
component: Layout,
children: [...autoLoadRoutes]
},
{
path: '/login',
name: 'login',
component: () => import('../views/login/index.vue')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
- vite写法
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
const pageModules = import.meta.glob("../pages/**/page.ts", {
eager: true,
import: "default",
});
const compModules = import.meta.glob("../pages/**/index.vue");
const routesMap: Array<RouteRecordRaw> = [];
Object.entries(pageModules).map(([pagePath, config]) => {
const path = pagePath.replace("../pages/", "").replace("/page.ts", "");
const compPath = pagePath.replace("page.ts", "index.vue");
routesMap.push({
path: `/${path}`,
name: path,
meta: config as any,
component: compModules[compPath],
});
});
const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "index",
redirect: "/home",
},
...routesMap,
];
const router = createRouter({
history: createWebHashHistory(),
routes,
});
export default router;
layout.vue
<script lang="ts" setup>
import { reactive } from 'vue'
import routers from '../router/index'
interface ILinks {
path: string
title: string
menuShow: boolean
menuSort: number
}
//获取所有路由,筛选isMenu为true的然后根据sort排序
const links = reactive(
routers
.getRoutes()
.map((r) => ({
path: r.path as string,
title: r.meta.title as string,
menuShow: !!r.meta.menuShow,
menuSort: r.meta.menuSort as number
}))
.filter((i) => i.menuShow)
.sort((r1: ILinks, r2: ILinks) => r1.menuSort - r2.menuSort)
)
</script>
结尾
以上是一个解决办法,我们的框架Django-Vue-Admin实现了一种更高效,更简单,更方便的方式,欢迎过来一起交流和探讨