hookehuyr

路由生成写法调整

1 /* 1 /*
2 * @Date: 2022-05-16 17:21:45 2 * @Date: 2022-05-16 17:21:45
3 * @LastEditors: hookehuyr hookehuyr@gmail.com 3 * @LastEditors: hookehuyr hookehuyr@gmail.com
4 - * @LastEditTime: 2022-06-29 06:19:41 4 + * @LastEditTime: 2022-06-29 16:00:23
5 * @FilePath: /tswj/src/utils/generateRoute.js 5 * @FilePath: /tswj/src/utils/generateRoute.js
6 * @Description: 文件描述 6 * @Description: 文件描述
7 */ 7 */
8 -/**
9 - * 生成动态路由
10 - */
11 import asyncRoutes from "../mock/routes" 8 import asyncRoutes from "../mock/routes"
12 9
13 -// 根据后台返回的路径,生成页面的组件模版 10 +/**
11 + * 根据后台返回的路径,生成页面的组件模版
12 + * @param {*} component
13 + * @returns 模版地址
14 + */
14 function loadView(component) { 15 function loadView(component) {
15 return () => import(`../views/${component}.vue`) 16 return () => import(`../views/${component}.vue`)
16 } 17 }
17 18
18 const formatRoutesArr = [] 19 const formatRoutesArr = []
19 20
20 -asyncRoutes.forEach(route => { 21 +/**
22 + * 生成路由结构
23 + * @param {*} routes 动态获取数据
24 + * @description 动态路由没有嵌套结构,children被拉平,都是平级的结构
25 + */
26 +const formatRoutes = (routes) => {
27 + routes.forEach(route => {
21 const router = {} 28 const router = {}
22 const { 29 const {
23 path, 30 path,
...@@ -35,13 +42,19 @@ asyncRoutes.forEach(route => { ...@@ -35,13 +42,19 @@ asyncRoutes.forEach(route => {
35 router.component = loadView(component) 42 router.component = loadView(component)
36 keepAlive && (router.keepAlive = keepAlive) 43 keepAlive && (router.keepAlive = keepAlive)
37 meta && (router.meta = meta) 44 meta && (router.meta = meta)
38 - if (children && children instanceof Array && children.length > 0) { 45 + router.children = !Array.isArray(children) || formatRoutes(children);
39 - router.children = formatRoutes(children)
40 - }
41 46
42 formatRoutesArr.push(router) 47 formatRoutesArr.push(router)
43 -}) 48 + })
49 +}
50 +
51 +formatRoutes(asyncRoutes)
44 52
53 +/**
54 + * 生成动态路由
55 + * @param {*} to
56 + * @returns 符合路径条件的动态路由结构
57 + */
45 export const generateRoute = (to) => { 58 export const generateRoute = (to) => {
46 let router = '' 59 let router = ''
47 formatRoutesArr.forEach(item => { 60 formatRoutesArr.forEach(item => {
......