实现效果:
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>