https://blog.csdn.net/tly599167/article/details/107378249/
一、动态菜单显示
下面是后端返回的数据:
[
{
“id”: “1”,
“pid”: “0”,
“name”: “工作台”,
“url”: “/dashboard”,
“icon”: “el-icon-s-platform”,
“children”: []
},
{
“id”: “2”,
“pid”: “0”,
“name”: “教务管理”,
“icon”: “el-icon-s-opportunity”,
“children”: [
{
“id”: “21”,
“pid”: “2”,
“name”: “学员中心”,
“url”: “/educate/student”
},
{
“id”: “22”,
“pid”: “2”,
“name”: “班级管理”,
“url”: “/educate/class”
},
{
“id”: “23”,
“pid”: “2”,
“name”: “课程管理”,
“url”: “/educate/course”
},
{
“id”: “24”,
“pid”: “2”,
“name”: “课表管理”,
“url”: “/educate/table”
}
]
},
{
“id”: “3”,
“pid”: “0”,
“name”: “系统设置”,
“icon”: “el-icon-s-opportunity”,
“children”: [
{
“id”: “31”,
“pid”: “3”,
“name”: “基础信息”,
“url”: “/setting/base”
},
{
“id”: “32”,
“pid”: “3”,
“name”: “职员管理”,
“url”: “/setting/user”
},
{
“id”: “33”,
“pid”: “3”,
“name”: “岗位管理”,
“url”: “/setting/role”
}
]
},
…
]
拿到后端的数据后,使用Vuex管理这些菜单数据。
{{group.name}}
{{menu.name}}
{{group.name}}
至此,通过后端返回的菜单数据动态生成菜单已完成。但是细心的小伙伴会发现,手动输入没有菜单的URL,仍然可以查看显示,这是不安全的,并且菜单栏无匹配项。
二、动态生成路由
/**
/**
export default new Router({
mode: ‘hash’,
base: process.env.BASE_URL,
routes: constantRouterMap // 这里只返回静态路由
})
/** store.js */
addUserMenus({ commit }, menus) {
commit(‘setMenuList’, menus)
// 扁平化菜单数据
const menuList = treeToList(menus.concat([]))
const addRoutes = []
let tempPath = ‘’
let tempList = []
// 这里只做了两层的路由处理
asyncRouterMap.forEach(item1 => {
tempPath = item1.path || ‘’
tempList = []
if (item1.children) {
item1.children.forEach(item2 => {
// TODO isLeaf是写死的,应该按照权限判断
if ((item2.meta && item2.meta.isLeaf) || menuList.find(o => o.url && path.join(tempPath, item2.path).toLowerCase() === o.url.toLowerCase())) {
tempList.push(item2)
}
})
}
if (tempList.length > 0) {
addRoutes.push(Object.assign({}, item1, {
children: tempList
}))
}
})
// 添加授权路由页面
Router.addRoutes(addRoutes)
}
treeToList方法
/**