const routes = [
{
path: '/',
name: '/',
component: 'layout/index',
meta: {
},
redirect: '/test1',
children: [
{
path: '/test1',
name: 'test1',
tag: '0',
component: 'views/test1/index',
meta: {
icon: 'location'
}
},
]
},
{
path: '/test2',
name: 'test2',
meta: {
icon: 'location'
},
component: 'layout/index',
redirect: '/test2-1',
children: [
{
path: '/test2-1',
name: 'test2-1',
meta: {
},
component: 'views/test2/index2-1'
},
{
path: '/test2-2',
name: 'test2-2',
meta: {
},
component: 'views/test2/index2-2'
},
]
},
{
path: '/test6',
name: 'test6',
meta: {
icon: 'location'
},
component: 'layout/index',
redirect: '/test6-1',
children: [
{
path: '/test6-1',
name: 'test6-1',
meta: {
},
component: 'views/test6/index6-1'
},
{
path: '/test6-2',
name: 'test6-2',
meta: {
},
tag: '1',
redirect: '/test6-2-1',
component: 'views/test6/index',
children: [
{
path: '/test6-2-1',
name: 'test6-2-1',
meta: {
},
component: 'views/test6/test6-2/index6-2-1',
},
{
path: '/test6-2-2',
name: 'test6-2-2',
meta: {
},
component: 'views/test6/test6-2/index6-2-2',
},
{
path: '/test6-2-3',
name: 'test6-2-3',
meta: {
},
component: 'views/test6/test6-2/index6-2-3',
},
]
},
]
},
]
let menu = []
function GenerateMenu(routes) {
// if(!routes[0].children){return 1}
let a = []
// 使用递归的话不能使用for...of...循环
// for (route of routes) {
// let menu_item = {}
// if (route.path === '/') {
// GenerateMenu([...route.children])
// }
// else {
// menu_item.label = route.meta.name
// menu_item.path = route.path
// if (route.meta && route.meta.icon) {
// menu_item.icon = route.meta.icon
// }
// if (route.tag && route.tag === '0') {
// menu.push(menu_item)
// }
// if (route.children) {
// // console.log(!route.tag)
// console.log(route.path)
// let route_copy = [...route.children]
// // console.log(route_copy)
// menu_item.children = GenerateMenu(route_copy)
// console.log(route.path)
// // console.log(route)
// //只在最深的一层打tag
// // if(!route.tag){
// // console.log(route)
// // menu.push(menu_item)
// // }
// }
// }
// a.push(menu_item)
// }
for (let i = 0; i < routes.length; i++) {
let menu_item = {}
if (routes[i].path === '/') {
GenerateMenu([...routes[i].children])
}
else {
menu_item.label = routes[i].meta.name
menu_item.path = routes[i].path
if (routes[i].meta && routes[i].meta.icon) {
menu_item.icon = routes[i].meta.icon
}
if (routes[i].tag && routes[i].tag === '0') {
menu.push(menu_item)
}
if (routes[i].children) {
// console.log(routes[i].path)
// js中的浅拷贝和深拷贝问题
// let route_copy = [...routes[i].children]
menu_item.children = GenerateMenu(routes[i].children)
if (!routes[i].tag) {
menu.push(menu_item)
}
}
}
a.push(menu_item)
}
return a
}
GenerateMenu(routes)
console.log(menu)
console