[学习笔记]VUE项目中令elementUI中的el-menu动态自适应数据

效果图:

第一步,配置<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
      }
    }
  }

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值