1.如下图是element原始菜单
在现实中菜单栏的目录数据往往存在数据库而element是写死的,下面进行改造,后端传多少显示多少,只有一级菜单的不显示下拉框 有二级的显示下拉图标
2.修改结果
如下图是修改过的效果图:

后端传过来的数据是map类型的 这里是模拟后端传过来的数据
"生产状态": [
{ index: 1, title: "选项1" },
{ index: 2, title: "选项2" },
],
"运行模式": [
{ index: 1, title: "选项1" },
{ index: 2, title: "选项2" },
],
"厂家": [
{ index: 1, title: "选项1" },
{ index: 2, title: "选项2" },
],
"售后": [], // 没有子菜单的例子
};
要下班了 下次想起来把代码贴上来吧再 这玩意自己写要好久(刚入门)AI真就五秒生成(GPT)
来贴代码了
<template>
<div class="menu">
<el-col class="content">
<el-menu
default-active="2" <!-- 默认激活的菜单项 -->
class="el-menu-vertical-demo"
@open="handleOpen"
@close="handleClose"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b"
>
<!-- 渲染每个菜单项 这里吐槽后端习惯了 key,value 这里看的很不习惯
menuData 是<script>标签里面定义的-->
<template v-for="(children, key) in menuData">
<!-- 如果子菜单为空或者长度为0,则渲染普通菜单项 -->
<el-menu-item v-if="!children || children.length === 0" :key="key" :index="key">
<i class="el-icon-location"></i>
<span>{{ key }}</span> <!-- 显示菜单项的名称 -->
</el-menu-item>
<!-- 如果有子菜单,则渲染为子菜单 -->
<el-submenu v-else :key="key" :index="key">
<template slot="title">
<i class="el-icon-location"></i>
<span>{{ key }}</span> <!-- 显示菜单项的名称 -->
</template>
<!-- 渲染子菜单项 -->
<el-menu-item
v-for="child in children"
:key="child.index"
:index="child.index.toString()"
>
{{ child.title }} <!-- 显示子菜单项的标题 -->
</el-menu-item>
</el-submenu>
</template>
</el-menu>
</el-col>
</div>
</template>
<script>
export default {
name: "NavMenu",
data() {
return {
menuData: {}, // 初始化为一个空对象
};
},
methods: {
handleOpen(key, keyPath) {
console.log("菜单打开:", key, keyPath);
},
handleClose(key, keyPath) {
console.log("菜单关闭:", key, keyPath);
},
fetchMenuData() {
// 模拟从后端获取菜单数据的方法
setTimeout(() => {
const responseData = {
"生产状态": [
{ index: 1, title: "选项1" },
{ index: 2, title: "选项2" },
],
"运行模式": [
{ index: 1, title: "选项1" },
{ index: 2, title: "选项2" },
],
"厂家": [
{ index: 1, title: "选项1" },
{ index: 2, title: "选项2" },
],
"售后": [], // 没有子菜单的例子
};
this.menuData = responseData;
console.log("菜单数据加载完成:", this.menuData);
}, 500); // 模拟延迟 500 毫秒
},
},
mounted() {
// 在组件挂载时获取菜单数据
this.fetchMenuData();
},
};
</script>
<style scoped>
.el-menu-vertical-demo {
background-color: #545c64;
color: #fff;
}
/* 使用 ::v-deep 穿透作用域来修改 active-text-color */
::v-deep .el-menu-vertical-demo .el-menu-item.is-active {
color: #ffd04b;
}
</style>