Ant Design of Vue
关于动态菜单的生成
项目较小时可以自己做动态菜单,代码简洁!!!
1、后端返回的菜单
2、格式化数据
export const listToTree = (list, tree, parentId) => {
list.forEach(item => {
// 判断是否为父级菜单
if (item.parentId == parentId) {
const child = {
path: item.url,
name: item.module,
children: [],
component: constantRouterComponents[item.module],
meta: { title: item.name, keepAlive: true, icon: item.icon || '', permission: [ 'dashboard' ] },
redirect: item.url
}
// 迭代 list, 找到当前菜单相符合的所有子菜单
listToTree(list, child.children, item.id);
// 删掉不存在 children 值的属性
if (child.children.length <= 0) {
delete child.children
}
if (child.meta.icon == '') {
delete child.meta.icon
}
// 加入到树中
tree.push(child)
}
})
}
格式化之后
{
path: '/index',
name: 'index',
component: BasicLayout,
meta: { title: '首页' },
children: [
{
path: '/index',
name: 'index',
component: () => import('@/views/account/index'),
meta: { title: '首页', keepAlive: false, permission: [ 'index' ] },
children: []
},
{
path: '/message',
name: 'message',
component: () => import('@/views/account/message'),
meta: { title: '消息', keepAlive: false, permission: [ 'index' ] },
children: []
},
{
path: '/base',
name: 'base',
component: () => import('@/views/account/base'),
meta: { title: '账户设置', keepAlive: false, permission: [ 'base' ] },
children: []
},
。。。more
3、去基础组件BasicLayout.vue文件中给菜单组件赋值
文件路径(src/layouts/BasicLayout.vue)
created () {
let that = this
axios('菜单接口',{}).then((res)=>{
const { data } = res;
const childrenNav = [];
// 格式化
listToTree(data, childrenNav, 0);
// router.config.js中的路由进行替换
asyncRouterMap[0].children = childrenNav;
// 生成菜单
that.menus = asyncRouterMap.find((item) => item.path === '/index').children;
that.collapsed = !that.sidebarOpened;
})
},
前期准备工作
Ant Design Pro官网链接
官网动态菜单配置过于繁琐,以上操作也能实现动态菜单,下期发自制的菜单的权限控制