什么是约定式路由?约定式路由也叫文件路由,就是不需要手写配置,文件系统即路由,通过目录和文件及其命名分析出路由配置。使用过 React 的同学应该都接触过 Umi 约定式路由 。
传统路由方式
使用过 Vue 的同学应该都知道,我们每新增一个页面,就需要去 router.js 中配置路由,这个工作简单且必须要去做,如果页面过多,就会导致路由文件代码臃肿,不好维护,我们常见的路由配置是这样的:
通过分析我们可以很轻易地发现,路由配置的 path、name、component 等信息都可以通过文件路径和名称统一获取,唯一不同的就是 meta 信息,这里我们就可以考虑把 meta 抽离出来,思路一下就出来了。
使用 glob API 匹配模块信息
-
首先我们先在 views 新建 meta.ts 文件,文件结构大概如下:
-
使用 glob 获取模块配置信息
const metaModules = import.meta.glob('../views/**/meta.ts')
这里我们就能得到整个模块的配置信息。
- 把配置信息映射成路由信息
const compModules = import.meta.glob('../views/**/index.vue')
// 把配置信息映射成路由信息
const routes = Object.entries(metaModules).map(([pagePath, config]) => {
// 匹配路由路劲
let path = pagePath.replace('../views', '').replace('/meta.ts', '')
// 判断是否根路径
path = path || '/'
// 匹配名称,,这里具体根据公司的要求
const name = path.split('/').filter(Boolean).join('-') || 'index'
const compPath = pagePath.replace('meta.ts', 'index.vue')
// 这里返回的就是每个路由的信息
return {
path,
name,
// 这不能这样写,生产环境会有问题
// component: () => import(component),
component: compModules[compPath],
meta: config
}
})
我们看一下最终 routes 的值,就是我们想要的结果:
- 最终 routes 的完整代码如下
import { createRouter, createWebHistory } from 'vue-router'
// 自动生成 routes
const metaModules = import.meta.glob('../views/**/meta.ts', {
eager: true,
import: 'default'
})
const compModules = import.meta.glob('../views/**/index.vue')
// 把配置信息映射成路由信息
const routes = Object.entries(metaModules).map(([pagePath, config]) => {
// 匹配路由路劲
let path = pagePath.replace('../views', '').replace('/meta.ts', '')
// 判断是否根路径
path = path || '/'
// 匹配名称,,这里具体根据公司的要求
const name = path.split('/').filter(Boolean).join('-') || 'index'
const compPath = pagePath.replace('meta.ts', 'index.vue')
// 这里返回的就是每个路由的信息
return {
path,
name,
// 这不能这样写,生产环境会有问题
// component: () => import(component),
component: compModules[compPath],
meta: config
}
})
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
})
export default router
约定式路由的作用
- 不用人工配置,只要按照文件约定配置好就可以了。
- 不用担心文件夹移动或者重命名引发组件引入的错误。
- 及时文件夹嵌套层次再深也能自动生成路由。
我感觉好处还是挺多的,哈哈
关注我的公众号,不定时分享软件开发技术文章和生活工作经验: