- 动态获取文件
// modules就是一个map,文件路径作为key,文件对象作为value
const modules=import.meta.glob('../views/**/*.vue')
获取到的modules对象如下:
- 添加动态路由
import {createRouter, createWebHashHistory} from 'vue-router'
const modules = import.meta.glob('../views/**/*.vue')
const constantRoutes = [
{
path: '/login',
name: 'login',
meta: {
title: '登录',
hidden: true
},
component: () => import('../views/login/index.vue')
},
]
const router = createRouter({
history: createWebHashHistory(),
routes:[…constantRoutes]
})
// 从后端动态获取的路由列表,[hidden:是否在侧边栏显示]
let dynamicRoutes = [
{
path: '/',
name: 'Layout',
redirect: '/home',
component: '/views/layout/index',
meta: {
title: 'Layout',
icon: 'HomeFilled',
hidden: false
},
children: [
{
path: '/home',
name: 'Home',
component: '/views/home/index',
meta: {
title: '首页',
icon: 'HomeFilled',
hidden: false
}
},
]
},
{
path: '/sys',
name: 'Sys',
component: '/views/layout/index',
meta: {
title: '系统管理',
icon: 'document',
hidden: false
},
children: [
{
path: '/sys/user',
name: 'User',
component: '/views/sys/user/index',
meta: {
title: '用户管理',
icon: 'document',
hidden: false
}
},
{
path: '/sys/role',
name: 'Role',
component: '/views/sys/role/index',
meta: {
title: '角色管理',
icon: 'document',
hidden: false
}
},
]
}
]
convertPathToComponent(dynamicRoutes)
addDynamicRoutes(dynamicRoutes)
// 添加动态路由
function addDynamicRoutes(dynamicRoutes) {
dynamicRoutes.forEach(item => {
router.addRoute(item)
})
}
// 使用递归将routeList中每个对象及其子对象中的component路径转换为组件(在component不为空的情况下)
function convertPathToComponent(dynamicRoutes) {
dynamicRoutes.forEach(item => {
if (item.component) {
item.component = modules['..' + item.component + '.vue'] || modules['../views/404/index.vue']
}
if (item.children) {
convertPathToComponent(item.children)
}
})
}
export default router