vue3 + ts 二次封装 el-menu

实现效果:

1. types / menu.ts

export interface MenuItem {
    index: string,
    label: string,
    icon?: string,
    disabled?: boolean,
    children?: MenuItem[],
}

2. components / CustomMenu / index.vue

<template>

  <el-menu :default-active="defaultActive">
    <custom-menu-item :menu-list="props.menuList"/>
  </el-menu>

</template>

<script setup lang="ts">

import CustomMenuItem from "@/components/CustomMenu/components/CustomMenuItem.vue";
import type {MenuItem} from "@/types/menu";

const props = defineProps<{
  menuList: MenuItem[],
  defaultActive?: string
}>()

</script>

<style scoped lang="scss">

</style>

3. components / CustomMenu / components / CustomMenuItem.vue

<template>

  <template v-for="menu in props.menuList" :key="menu.index">
    <el-sub-menu v-if="menu.children" :index="menu.index" :disabled="menu.disabled">
      <template #title>
        <el-icon v-if="menu.icon">
          <component :is="menu.icon"/>
        </el-icon>
        <span>{{ menu.label }}</span>
      </template>
      <custom-menu-item :menu-list="menu.children"/>
    </el-sub-menu>
    <el-menu-item v-else :index="menu.index" :disabled="menu.disabled">
      <el-icon v-if="menu.icon">
        <component :is="menu.icon"/>
      </el-icon>
      <span>{{ menu.label }}</span>
    </el-menu-item>
  </template>

</template>

<script setup lang="ts">

import type {MenuItem} from "@/types/menu";

const props = defineProps<{
  menuList: MenuItem[]
}>()

</script>

<style scoped lang="scss">

</style>

4. 使用 test.vue

<template>

  <div class="custom-menu-container">
    <custom-menu :menu-list="menuList" :default-active="defaultActive"/>
  </div>

</template>

<script setup lang="ts">

import CustomMenu from '@/components/CustomMenu/index.vue'

const defaultActive = '1-1'

import type {MenuItem} from "@/types/menu";

const menuList: MenuItem[] = [
    {
        index: '1',
        label: '菜单1',
        icon: 'House',
        children: [
            {
                index: '1-1',
                label: '菜单1-1',
                // icon: 'Connection'
            },
            {
                index: '1-2',
                label: '菜单1-2',
                // icon: 'ChatDotRound'
            }
        ]
    },
    {
        index: '2',
        label: '菜单2',
        icon: 'Notification',
        children: [
            {
                index: '2-1',
                label: '菜单2-1',
                // icon: 'Setting'
            }
        ]
    },
    {
        index: '3',
        label: '菜单3',
        icon: 'Odometer'
    }
]

</script>

<style scoped lang="scss">

.custom-menu-container {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 200px;
  height: fit-content;
}

</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值