vue3+elementui-plus实现无限递归菜单

效果图

实现方式是:通过给定的数据结构层数来动态生成多级菜单

复制代码
menu.vue

<template>
  <el-menu
      :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      @select="handleSelect"
      background-color="#f8f8f9"
      style="margin-top: 20px;margin-left: 1px;"
  >
    <Childrenmenu v-for="menuItem in menuItems" :key="menuItem.value" :item="menuItem" />
  </el-menu>
</template>

<script setup>
import Childrenmenu from "./childrenmenu";
const menuItems = [
	  {
	    value: '1',
	    label: '菜单1',
	    children: [
	      {
	        value: '1-1',
	        label: '子菜单1-1',
	        children: [
	          { value: '1-1-1', label: '子菜单1-1-1' },
	          { value: '1-1-2', label: '子菜单1-1-2' },
	        ],
	      },
	      { value: '1-2', label: '子菜单1-2' },
	    ],
	  },
	  {
	    value: '2',
	    label: '菜单2',
	    children: [
	      { value: '2-1', label: '子菜单2-1' },
	      {
	        value: '2-2',
	        label: '子菜单2-2',
	        children: [
	          { value: '2-2-1', label: '子菜单2-2-1' },
	          { value: '2-2-2', label: '子菜单2-2-2' },
	        ],
	      },
	    ],
	  },
	  {
	    value: '3',
	    label: '菜单3',
	    children: [
	      {
	        value: '3-1',
	        label: '子菜单3-1',
	        children: [
	          {
	            value: '3-1-1',
	            label: '子菜单3-1-1',
	            children: [
	              { value: '3-1-1-1', label: '子菜单3-1-1-1' },
	              { value: '3-1-1-2', label: '子菜单3-1-1-2' },
	            ],
	          },
	        ],
	      },
	    ],
	  },
	];
	
const handleSelect = async (key, keyPath) => {
	 console.log(key, keyPath)
}
</script>

childrenmenu.vue

<template>
  <template v-if="item.children">
    <el-sub-menu :index="item.value">
      <template #title>{{ item.label }}</template>
      <Childrenmenu v-for="childItem in item.children" :key="childItem.value" :item="childItem" />
    </el-sub-menu>
  </template>
  <template v-else>
    <el-menu-item :index="item.value">{{ item.label }}</el-menu-item>
  </template>
</template>

<script setup>
import { defineProps } from 'vue';

const props = defineProps(['item']);
</script>

<style scoped>

</style>
相关推荐
kyriewen3 分钟前
MutationObserver:DOM界的“卧底”,暗中观察每个风吹草动
前端·javascript·面试
踩着两条虫8 分钟前
VTJ.PRO 在线应用开发平台的开发者工具与代码质量
前端·vue.js·ai编程
TON_G-T17 分钟前
100行实现Mini React
前端·javascript·react.js
恋猫de小郭17 分钟前
2026 AI 时代下,Flutter 和 Dart 的机遇和未来发展,AI 一体化
android·前端·flutter
1314lay_100728 分钟前
Element Plus左侧侧边栏按照屏幕宽度来确定显示和隐藏,如果太小的话,侧边栏消失,菜单会变成一个小按钮,点击按钮以模态框弹出
javascript·vue.js·elementui
看客随心31 分钟前
vue + elementPlus大屏项目使用autofit做适配及注意点
前端·javascript·vue.js
网络点点滴1 小时前
Vue3 全局API转移到应用对象
前端·javascript·vue.js
波哥学开发1 小时前
基于 OPFS 的前端缓存实践:图片与点云数据的本地持久化
前端
whuhewei1 小时前
useCountDown (React Hooks)倒计时
前端·javascript·react.js