上篇文章虽然实现了动态路由的功能,但是还是很麻烦的,需要配置两套路由表才能实现,经过一系列的测试后,动态路由表的配置完全由后端返回的路由数据进行生成。
菜单表(menu_table):
menuId | pid | title | path | name | redirect | component | alwaysShow | hidden | noCache | activeMenu | icon | type | sort |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
菜单id | 菜单父级id | 菜单标题 | 菜单path | 菜单name | 路由重定向地址 | 路由组件 | 始终显示 | 隐藏路由 | 不缓存路由 | 突出显示菜单 | 路由图标 | 菜单类型 | 菜单排序 |
这么写了之后就不需要用两套路由去进行递归取相同的路由了。只需把后端返回的路由信息进行递归处理就行了,store/modules/permission.js中引入Layout:
import Layout from '@/layout'
优化后的路由处理函数:
export function recursiveAsyncRoutes(userRouterList) {
let res = [];
userRouterList.forEach(route => {
let item = {
path: route.path,
redirect: route.redirect,
name: route.name,
meta: {
title: route.title,
icon: route.icon,
}
};
!!route.alwaysShow && (item.alwaysShow = true);
!!route.noCache && (item.meta.noCache = true);
!!route.activeMenu && (item.meta.activeMenu = route.activeMenu);
!!route.hidden && (item.hidden = true);
if (route.component) {
if (route.component === 'Layout') {
item.component = Layout;
} else {
item.component = () => import(`@/views/${route.component}`)
}
}
if (route.children) {
item.children = recursiveAsyncRoutes(route.children);
}
res.push(item)
})
return res;
}
这个时候就不需要前端再配置异步路由数据了。