vue 动态路由

路由由后端返回平面数组

需要先由一下方法转化为树形路由结构

parentId为父集id,为0时作为最高级

export function convertRoutesToMenu( routes ) {
    let parent = routes.filter(route => route.parentId === '0');
    let children = routes.filter(route => route.parentId !== '0');
    dataToTree(parent, children);

    function dataToTree( parent, children ) {
        parent.map(( item ) => {
            children.map(( child, index ) => {
                if (item.menuId === child.parentId) {
                    let _c = JSON.parse(JSON.stringify(children));
                    _c.splice(index, 1)
                    dataToTree([child], _c);

                    if (item.children) {
                        item.children.push(child);
                    } else {
                        item.children = [child];
                    }
                }
            })
        })
    }


    return parent;
}

将树形结构转换为可用的路由结构

export function generateRouter( userRouters ) {
    // const modules = import.meta.glob('@/views/**/*.vue');
    let newRouters = userRouters.map(( r ) => {
        let routes = {
            path: r.component,
            name: r.query,
            meta: { title: r.menuNam },
            component: () => import(`@/views/${r.path}/index`)
            // component:() => modules[`@/views/${r.name}`]
        }
        if (r.children) {
            routes.children = generateRouter(r.children);
        }
        return routes;
    })
    return newRouters;
}

动态添加路由

import router from '@/router'

 router.addRoute('父集路由名', 路由)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值