自动化导入路由

起因:

当项目过大时,路由越来越多时,免不了一个文件一个文件的手动引入,这样不仅繁琐,而且导致文件过大。

image.png

解决办法:使用路由自动化导入

目录结构图

image.png

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实现了一种更高效,更简单,更方便的方式,欢迎过来一起交流和探讨

image.png

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值