generateRoute.js
1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* @Date: 2022-05-16 17:21:45
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2022-06-29 17:00:15
* @FilePath: /tswj/src/utils/generateRoute.js
* @Description: 动态路由组装(把后端路由数据转换成 vue-router 结构)
*/
/**
* 根据后端返回的 component 字段,生成对应页面的动态 import
* @param {string} component views 下的页面文件名(不含 .vue)
* @returns {() => Promise<any>} 组件加载函数
*/
function loadView(component) {
return () => import(`../views/${component}.vue`)
}
/**
* 生成路由结构
* @param {Array<Object>} routes 后端路由数组
* @returns {Array<Object>} vue-router routes 数组
*/
const generateRoutes = (routes) => {
const arr = []
routes.forEach(route => {
const router = {}
const {
path,
redirect,
name,
component,
keepAlive,
meta,
children
} = route
router.path = path
redirect && (router.redirect = redirect)
name && (router.name = name)
router.component = loadView(component)
keepAlive && (router.keepAlive = keepAlive)
meta && (router.meta = meta)
// children 不是数组时,统一置空,避免生成 true 导致路由结构异常
router.children = Array.isArray(children) ? generateRoutes(children) : [];
arr.push(router)
})
return arr
}
export default generateRoutes;