效果图:
第一步,配置<el-menu>,利用v-if和v-else语句操作逻辑(是否显示子菜单),利用v-for进行循环赋值将数组数据赋值给item已经创建菜单项。
<el-menu
router :default-active="this.$router.path"
class="el-menu-vertical-demo"
@open="handleOpen"
@close="handleClose"
:collapse="isCollapse">
<!--使用v-if语句进行判断有无children菜单,确定一级菜单是否需要下拉功能-->
<el-submenu :index="item.path" v-for="item in arrType" :key="item.key"
v-if="subtitleIsExist(item)">
<!--一级菜单在submenu中为下拉状态-->
<template slot="title">
<i :class=item.icon></i>
<span>{{item.title}}</span>
</template>
<!--二级菜单再次进行v-if判断是否显示二级菜单-->
<el-menu-item
:index="item2.path"
v-for="item2 in item.children"
:key="item2.key"
v-if="subtitleIsExist(item)">
<template slot="title">{{item2.title}}</template>
</el-menu-item>
</el-submenu>
<!--一级菜单使用v-else在不在submenu中为非下拉状态-->
<el-menu-item :index="item.path" v-else>
<template slot="title">
<i :class=item.icon></i>
<span>{{item.title}}</span>
</template>
</el-menu-item>
</el-menu>
第二步,配置列表数据数组。
data () {
return {
// 是否折叠显示菜单栏
isCollapse: true,
// 侧边栏数据
arrType: [
{
key: 'menu-1',
title: '一级菜单1',
path: '/home/test',
icon: 'el-icon-notebook-2',
children: [
{
key: 'menu-1-1',
title: '二级菜单1',
path: '/home/test'
},
{
key: 'menu-1-2',
title: '二级菜单2',
path: '/home/test2'
}
]
},
{
key: 'menu-2',
title: '一级菜单2',
path: '/home/test2',
icon: 'el-icon-pie-chart',
children: [
{
key: 'menu-2-1',
title: '二级菜单3',
path: '/home/test3'
},
{
key: 'menu-2-2',
title: '二级菜单4',
path: '/home/test4'
}
]
},
{
key: 'menu-3',
title: '一级菜单3',
path: '/home/test2',
icon: 'el-icon-suitcase'
}
]
}
}
第三步,配置判断是否存在子菜单函数。
methods: {
handleOpen (key, keyPath) {
console.log(key, keyPath)
},
handleClose (key, keyPath) {
console.log(key, keyPath)
},
// 判断菜单是否有子菜单
subtitleIsExist (item) {
if (item.children) {
return true
} else {
return false
}
}
}