1. 程式人生 > 其它 >Vue許可權動態路由Array轉成功Tree

Vue許可權動態路由Array轉成功Tree

技術標籤:親測:真的可用

<!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>