路由由后端返回平面数组
需要先由一下方法转化为树形路由结构
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 ) {
let newRouters = userRouters.map(( r ) => {
let routes = {
path: r.component,
name: r.query,
meta: { title: r.menuNam },
component: () => import(`@/views/${r.path}/index`)
}
if (r.children) {
routes.children = generateRouter(r.children);
}
return routes;
})
return newRouters;
}
动态添加路由
import router from '@/router'
router.addRoute('父集路由名', 路由)