一般来说,公司对项目的文件目录这一块都会有一个约定,比如我们的页面都放在views文件夹内,然后每个页面入口都是index.vue或者index.jsx这种 我们公司就约定如下图
error是错误页面
pages是菜单页面
business-page是一些特殊的业务页面
Auth.vue是未抽离的鉴权页面
index是入口页
那么按照这种结构,其实,路由的规律,已经出来了,直接上代码
const getDynamicRoutes = (menus) => {
const files = import.meta.glob('@/views/pages/**/*.vue', { eager: true })
const Maps = {}
Object.keys(files).forEach((key) => {
const menuCode = key.slice(16, -4).toLowerCase()
Maps[menuCode] = files[key].default
})
const path = {}
return menus
.filter((it) => {
const r = !path[it.code] && Maps[it.code]
path[it.href] = true
return r
})
.map((it) => {
return {
path: it.href,
name: it.code,
meta: {
title: it.name,
active: it.code,
hasCache: it.hasCache,
sort: it.sort
},
component: Maps[it.code]
}
})
}
const errorRoutes = [
{
path: '/404',
name: '404',
component: () => import('../views/error/404.vue')
},
{
path: '/:pathMatch(.*)',
redirect: '/404'
}
]
一切都是根据企业内部规范与约定
其余即可与vue2的写法一样去注入动态路由规则