使用require.context根据views文件夹下(多级文件夹)所有.vue文件路径实现路由自动匹配生成如下格式routes,routes: [{ path: '/', redirect: '/login' }, { path: '/home', name: 'home', component: () => import('@/views/Home.vue'), redirect: '/main', children: [{ path: '/main', name: 'main', component: () => import('@/views/Main/index.vue'), children: [{ path: '/xxx', name: 'xxx', component: () => import('@/views/Main/Xxx.vue'), }, { path: '/yyy', name: 'yyy', component: () => import('@/views/Main/Yyy.vue'), } ] }, { path: '/zz', name: 'zz', component: () => import('@/views/Zz/index.vue'), children: [{ path: '/mmm', name: 'mmm', component: () => import('@/views/Zz/Mmm.vue'), }] }, ] }, { path: '/login', name: 'login', component: () => import('@/views/Login.vue') } ]
时间: 2023-12-25 11:05:47 浏览: 165
你可以使用以下代码实现:
```js
const files = require.context('@/views', true, /\.vue$/)
const routes = []
files.keys().forEach(key => {
const name = key.match(/\/(\w+)\.vue$/)[1]
const path = key.replace(/^\.\//, '').replace(/\.vue$/, '').replace(/\/index$/, '')
const route = {
path: `/${path name: name,
component: files(key).default
}
if (path === 'Home') {
route.redirect = '/main'
route.children = [{
path: 'main',
name: 'main',
component: () => import('@/views/Main/index.vue'),
children: [{
path: 'xxx',
name: 'xxx',
component: () => import('@/views/Main/Xxx.vue')
}, {
path: 'yyy',
name: 'yyy',
component: () => import('@/views/Main/Yyy.vue')
}]
}, {
path: 'zz',
name: 'zz',
component: () => import('@/views/Zz/index.vue'),
children: [{
path: 'mmm',
name: 'mmm',
component: () => import('@/views/Zz/Mmm.vue')
}]
}]
}
routes.push(route)
})
routes.push({
path: '/',
redirect: '/login'
}, {
path: '/login',
name: 'login',
component: () => import('@/views/Login.vue')
})
export default routes
```
这里使用了 `require.context` 获取所有 `.vue` 文件,然后通过正则表达式获取文件名和路径,最后根据路径和组件生成路由对象,如果是 `Home` 组件,则添加子路由。最后还要添加默认路由和登录路由。
阅读全文