一次在项目中需要动态获取侧边栏菜单。
我使用了一种简单粗暴的方法。
修改侧边栏组件,这里存放的就是侧边栏样式。
将index.vue
备份然后删除里面的内容,修改为下面的,这样每次请求就会发送请求获取相应的菜单栏然后遍历出来。
<template>
<div class="cen">
<el-menu
router
class="el-menu-vertical-demo"
:collapse="isCollapse"
background-color="#333744"
text-color="#fff"
active-text-color="#409FFF"
>
<el-submenu v-for="(item,i) in menus" :key="i" class="menu" :index="item.path">
<template v-if="item.children || item.children === null" slot="title">
<i :class="item.meta.icon" />
<span slot="title">{ { item.name } }</span>
</template>
<el-menu-item v-if="!item.children || item.children === null" :key="i" :index="item.path">
<i :class="item.meta.icon" />
<span slot="title">{ { item.name } }</span>
</el-menu-item>
<div v-if="item.children">
<el-menu-item
v-for="(arr,a) in item.children"
v-if="!(arr.hidden)"
:key="a"
:index="arr.path"
class="menu-item"
>
<i :class="arr.meta.icon" />
<span slot="title">{ { arr.name } }</span>
</el-menu-item>
</div>
</el-submenu>
</el-menu>
</div>
</template>
<style>
.menu .menu-item .menu:hover {
min-width: 210px !important;
background-color: #1f2d3d !important;
}
.cen {
background-color: #ffffff;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
background-color: #ffffff;
width: 200px;
min-height: 400px;
}
</style>
<script>
import q from '@/utils/areq'
export default {
data() {
return {
isCollapse: false,
menus: []
}
},
mounted() {
this.getmenus()
},
methods: {
handleOpen(key, keyPath) {
console.log(key, keyPath)
},
handleClose(key, keyPath) {
console.log(key, keyPath)
},
getmenus() {
q.get('/menus').then(res => {
this.menus = res.data
})
}
}
}
</script>