双循环递归匹配路由表
/** *根据后端返回数据要求,导航栏权限返回的是要展示的所以信息,所以我们只能根据返回的对象去匹配我们的路由表,把没有返回的项再路由表里剔除,然后重新生成路由表 */ // 此处数据皆为模拟操作,真是数据请结合实际情况获取 data: { route: [ // 我们定义好的路由表 {path:"/",name:"a",hidden:true}, {path:"/b",name:"b",hidden:true,children:[ {path:"/b_1",name:"b_1",hidden:true}, {path:"/b_2",name:"b_2",hidden:true}, ]}, {path:"/c",name:"c",hidden:true,children:[ {path:"/c_1",name:"c_1",hidden:true}, {path:"/c_2",name:"c_2",hidden:true}, {path:"/c_3",name:"c_3",hidden:true}, ]}, {path:"/d",name:"d",hidden:true}, ], permisRoute: [ // 后端返回的路由表权限 {name:"a"}, {name:"b",permission:[ {name:"b_1"}, ]}, {name:"c",permission:[ {name:"c_1"}, {name:"c_2"}, ]}, ] }, methods: { /** * [此处方法应写store里,然后再在beforeEach里去动态添加路由,vue2.0提供了addRoutes方法 * @param {[type]} route [router里面自己定义好的路由表] * @param {[type]} permisRoute [后台返回路由表权限] * @return {[type]} [生成新的路由表] */ filterRoute: function(route,permisRoute) { for(let item of permisRoute){ const name = item.name; for(let item of route){ // 修改hidden,匹配路由表 if(item.name == name){ item.hidden = false; break; } } if(item.permission){ const permisRouteChild = item.permission; const routeChild = route.filter(itme => { return itme.name == name; }) // 递归路由表 this.filterRoute(routeChild[0].children,permisRouteChild) } } return route }, filtersHidden: function (arr) { // 上一步只是把里面hidden变成true,把filterRoute返回结果传入此函数可以过滤掉hidden为true的对象 const accessedRouters = arr.filter(route => { if(!route.hidden){ if (route.children && route.children.length) { route.children = this.filtersa(route.children) } return true } }) return accessedRouters }, }
逻辑可能有点复杂,如果有更好的方法请指教