我司最近正在用VUE做一个基于用户权限显示不同左侧菜单的后台管理系统,接口会根据用户的权限不同返回不同的菜单名称、URL等,前端要将这些菜单名称及URL动态添加到系统的左侧,这里就用到了vue-router2.2
新添的router.addRouter(routes)
方法。但是接口返给我的只是普通的由键值对组成的数组,而vue-router
需要的是固定格式的路由写法,于是我就只能自己动手将普通的数组转换成路由的写法了。具体代码如下:
let json = [
{
"id": 64,
"code": "565",
"name": "*",
"label": "*",
"parentId": 0,
"type": 2,
"seq": 0,
"url": "/public",
"description": "同意",
"children": []
},
{
"id": 1,
"code": "sys_mgnt",
"name": "系统管理",
"label": "系统管理",
"parentId": 0,
"type": 1,
"url": "/system",
"seq": 1,
"description": "aaa",
"children": [
{
"id": 28,
"name": "测试二级菜单1",
"label": "测试二级菜单1",
"parentId": 1,
"type": 1,
"url": "/add",
"seq": 1,
"description": "测试二级菜单的描述",
"children": [
{
"id": 288,
"name": "三级菜单1",
"label": "三级菜单1",
"parentId": 11,
"type": 1,
"url": "/add1",
"seq": 1,
"description": "三级菜单1的描述",
"children": []
}
]
},
{
"id": 30,
"name": "新增角色管理",
"label": "新增角色管理",
"parentId": 1,
"type": 2,
"seq": 1,
"description": "新增角色管理的描述",
"children": []
},
{
"id": 31,
"name": "add角色管理",
"label": "add角色管理",
"parentId": 1,
"type": 1,
"seq": 1,
"description": "add角色管理的描述",
"children": []
},
{
"id": 3,
"code": "ro_mgnt",
"name": "角色管理",
"label": "角色管理",
"parentId": 1,
"type": 1,
"url": "",
"seq": 2,
"children": [
{
"id": 32,
"name": "可以成功",
"label": "可以成功",
"parentId": 3,
"type": 2,
"url": "/ctrl",
"seq": 1,
"description": "能成功吗的描述",
"children": []
}
]
}
]
}
]
let routerArr = JSON.parse(JSON.stringify(json));
function formatRoutes(routerArr){
const arr = [];
let obj = {};
routerArr.forEach(router => {
const tmp = { ...router };
if(tmp.type == 1){ //只筛选出type=1的项
if (tmp.children) {
tmp.children = formatRoutes(tmp.children);
const {url, children, type} = router;
obj = {
path: tmp.url,
name: tmp.name,
meta: {title: tmp.name},
children: tmp.children
}
}
arr.push(obj);
}
})
return arr;
}
let routers = formatRoutes(routerArr);
console.log(routers);
输出的结果为:
很明显这就已经符合了路由的基本写法,只是在每一个路由配置中少了一个component,所以接口返给我们的数组即使我们通过递归遍历生成了我们想要的东西,但是依旧不能满足前端的配置需求,个人建议接口返回固定的路由配置格式且返回的路由应该是前端提前已经配好的,不然我们的component里边的路径写啥?不然我们要跳转的页面在哪儿?不过这不是本文讨论的重点!