el-menu两级级菜单
时间: 2025-01-16 10:10:59 浏览: 46
### 创建 Element UI 的两级联动菜单
为了创建一个带有 `el-menu` 组件的两级联动菜单,可以利用 Vue.js 和 Element UI 提供的功能来构建动态菜单结构。下面是一个完整的示例代码片段,展示了如何通过 `v-for` 循环渲染不同的子标签 (`el-menu-item` 和 `el-submenu`) 来实现这一目标。
#### HTML 结构与模板部分
```html
<template>
<div id="app">
<!-- 定义导航栏 -->
<el-menu :default-active="$route.path" router unique-opened mode="vertical"
background-color="#545c64" text-color="#fff" active-text-color="#ffd04b">
<!-- 外层循环遍历顶级菜单项 -->
<el-submenu v-for="(item, index) in menuData" :key="index" :index="String(index)">
<template slot="title"><i class="el-icon-location"></i>{{ item.title }}</template>
<!-- 内层循环遍历次级菜单项 -->
<el-menu-item-group>
<el-menu-item v-for="(subItem, subIndex) in item.children" :key="subIndex" :index="subItem.index">{{ subItem.title }}</el-menu-item>
</el-menu-item-group>
</el-submenu>
</el-menu>
</div>
</template>
```
#### JavaScript 部分 (Vue 实例)
```javascript
<script>
export default {
data() {
return {
// 菜单数据源定义
menuData: [
{ title: '首页', children: [{ title: '概览', index: '/overview' }] },
{ title: '产品管理',
children: [
{ title: '新增商品', index: '/product/add' },
{ title: '编辑商品', index: '/product/edit' }
]
},
{ title: '订单处理',
children: [
{ title: '待发货列表', index: '/order/pending' },
{ title: '已发货列表', index: '/order/shipped' }
]
}
],
};
},
};
</script>
```
此配置实现了如下功能:
- 使用 `el-menu` 组件作为容器,并设置了默认激活路径 `$route.path`[^2]。
- 应用了 `unique-opened` 属性确保每次只展开一个二级菜单[^1]。
- 设置了背景颜色、文字颜色以及激活状态下文字的颜色属性以增强视觉效果[^1]。
- 对于每一组父级菜单及其下的子菜单分别进行了两次 `v-for` 迭代操作,从而完成了两层嵌套关系的数据绑定。
阅读全文
相关推荐


















