vue-admin-template、vue-element-admin配置动态菜单,菜单数据从后台获取。 我在网上search了几个小时也没有找到想要的emm,翻官网也没有说明,只说明了路由覆盖。只能自己手撸试调,并实现了该功能。因为场景一般都是根据不同角色访问不同菜单的。 首先这是我后台传来的菜单:
{
"code":0,
"msg":null,
"data":[
{
"id":1,
"parentId":0,
"title":"仪表盘",
"path":"/dashboard",
"icon":"dashboard",
"sortNumber":1,
"status":"1"
},
{
"id":2,
"parentId":0,
"title":"表单",
"path":"/form/index",
"icon":"form",
"sortNumber":2,
"status":"1"
},
{
"id":3,
"parentId":0,
"title":"nested",
"path":"/nested",
"icon":"nested",
"sortNumber":1,
"status":"1"
},
{
"id":4,
"parentId":3,
"title":"menu1",
"path":"/menu1",
"icon":null,
"sortNumber":1,
"status":"1"
},
{
"id":7,
"parentId":3,
"title":"menu2",
"path":"/nested/menu2",
"icon":null,
"sortNumber":2,
"status":"1"
},
{
"id":5,
"parentId":4,
"title":"menu1-1",
"path":"/nested/menu1/menu1-1",
"icon":null,
"sortNumber":1,
"status":"1"
},
{
"id":6,
"parentId":4,
"title":"menu1-2",
"path":"/nested/menu1/menu1-2",
"icon":null,
"sortNumber":2,
"status":"1"
}
]
}
在api中定义了获取菜单的请求函数
export function getMenus() {
return request({
url: '/user/menus',
method: 'get'
})
}
在src\layout\components\Sidebar\index.vue 中
<sidebar-item v-for="route in requestMenus" :key="route.path" :item="route" :base-path="route.path" />
import { getMenus } from '@/api/user'
data() {
return {
requestMenus: []
}
},
created() {
this.menus()
},
methods: {
menus() {
getMenus().then(res => {
this.requestMenus = this.listToTree(res.data, 0)
})
}, listToTree(list, parentId) {
const tree = []
for (let i = 0; i < list.length; i++) {
const temp = list[i]
temp.meta = { title: temp.title, icon: temp.icon }
if (temp.parentId === parentId) {
temp.children = this.listToTree(list, temp.id)
tree.push(temp)
}
}
return tree
}
}
以上配置的前提是router/index.js中的路由,能匹配后台传来路由路径。原来写死的路由配置我没有修改过 效果
|