vue 实现多级菜单
Vue 实现多级菜单的方法
递归组件实现
递归组件是实现多级菜单的核心技术。通过组件调用自身,可以动态渲染任意层级的菜单结构。
<template>
<ul>
<li v-for="item in menuData" :key="item.id">
{{ item.name }}
<menu-item v-if="item.children" :menu-data="item.children"></menu-item>
</li>
</ul>
</template>
<script>
export default {
name: 'MenuItem',
props: {
menuData: Array
}
}
</script>
数据结构设计
合理的菜单数据结构是基础,推荐使用嵌套对象形式:
const menuData = [
{
id: 1,
name: '一级菜单',
children: [
{
id: 11,
name: '二级菜单',
children: [...]
}
]
}
]
动态样式处理
为不同层级菜单添加样式差异,增强用户体验:
ul {
list-style: none;
padding-left: 20px;
}
li {
cursor: pointer;
padding: 5px 10px;
}
li:hover {
background-color: #f0f0f0;
}
状态管理
使用Vuex或Pinia管理菜单展开/折叠状态:
// store.js
export const useMenuStore = defineStore('menu', {
state: () => ({
expandedItems: []
}),
actions: {
toggleExpand(id) {
const index = this.expandedItems.indexOf(id)
if (index > -1) {
this.expandedItems.splice(index, 1)
} else {
this.expandedItems.push(id)
}
}
}
})
路由集成
将菜单与Vue Router集成,实现导航功能:
const routes = [
{
path: '/products',
component: Products,
children: [
{
path: 'category',
component: Category
}
]
}
]
性能优化
对于大型菜单数据,可采用虚拟滚动技术:
<template>
<RecycleScroller
:items="flattenedMenuData"
:item-size="50"
key-field="id"
>
<template #default="{ item }">
<div :style="{ paddingLeft: `${item.level * 20}px` }">
{{ item.name }}
</div>
</template>
</RecycleScroller>
</template>
响应式设计
添加移动端适配处理:
@media (max-width: 768px) {
.menu-container {
position: fixed;
top: 0;
left: 0;
width: 80%;
height: 100vh;
background: white;
transform: translateX(-100%);
transition: transform 0.3s ease;
}
.menu-container.active {
transform: translateX(0);
}
}
无障碍支持
增强菜单的可访问性:
<li
role="menuitem"
:aria-expanded="isExpanded(item.id)"
@keydown.enter="toggleExpand(item.id)"
>
{{ item.name }}
</li>






