如何用Vue3 + TypeScript 封装侧边栏el-menu菜单组件
<template>
<el-menu
:default-active="defaultActive"
class="el-menu-vertical-demo"
@open="handleOpen"
@close="handleClose"
>
<template v-for="item in menuItems" :key="item.index">
<el-sub-menu v-if="item.children && item.children.length" :index="item.index">
<template #title>
<i :class="item.icon"></i>
<span>{{ item.title }}</span>
</template>
<side-menu-item
v-for="subItem in item.children"
:key="subItem.index"
:item="subItem"
/>
</el-sub-menu>
<el-menu-item v-else :index="item.index">
<i :class="item.icon"></i>
<template #title>{{ item.title }}</template>
</el-menu-item>
</template>
</el-menu>
</template>
<script lang="ts">
import { defineComponent, PropType } from 'vue';
import type { MenuItem } from './types';
export default defineComponent({
name: 'SideMenu',
props: {
menuItems: {
type: Array as PropType<MenuItem[]>,
default: () => [],
},
defaultActive: {
type: String,
default: '',
},
},
setup(props, { emit }) {
const handleOpen = (index: string, indexPath: string) => {
emit('open', index, indexPath);
};
const handleClose = (index: string, indexPath: string) => {
emit('close', index, indexPath);
};
return {
handleOpen,
handleClose,
};
},
});
</script>
这个代码实例展示了如何在Vue 3和TypeScript中创建一个可以接收menuItems
属性的侧边栏菜单组件。它使用了el-menu
和el-sub-menu
组件来构建多级菜单,并通过props
传递菜单数据。setup
函数中定义了处理菜单打开和关闭事件的方法,并通过emit
将这些事件向上传递给父组件。
评论已关闭