Vue权限动态路由Array转成功Tree
程序员文章站
2022-05-14 15:54:22
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function dataTree(data) {
let parents = data.filter(c => c.pid == 0),
childrens = data.filter(c1 => c1.pid != 0);
tree(parents, childrens)
/**
* 求这先求出第一层的数据
*/
function tree(parents, childrens) {
parents.map((v, i1) => {
childrens.map((c, i) => {
if (v.id == c.pid) {
let _c = JSON.parse(JSON.stringify(childrens))
_c.splice(i, 1)
if (v.children) {
v.children.push(c)
} else {
v.children = [c]
}
tree([c], [_c])
}
})
})
}
return parents;
}
let arr = [
{ pid: 0, id: 1, path: '/a', name: "s" },
{ pid: 1, id: 6, name: 'f', path: '/a', },
{ pid: 1, id: 7, name: 'g', path: '/a', },
{ pid: 0, id: 2, name: 'b', path: '/a', },
{ pid: 0, id: 3, name: 'c', path: '/a', },
{ pid: 0, id: 4, name: 'd', path: '/a', },
{ pid: 0, id: 5, name: 'e', path: '/a', },
]
const routerarr = dataTree(arr);
function routerTemplate(routers) {
const routes = routers.map((v, i) => {
let router = {
path: v.path,
name: v.name,
component: () => import(`${v.path}`)
}
if (v.children) {
router.children = routerTemplate(v.children)
}
return router
})
return routes
}
console.log(routerTemplate(routerarr))
</script>
</body>
</html>