当前位置: 首页 > 工具软件 > Path-Menu > 使用案例 >

el-menu实现多级菜单效果

程仲卿
2023-12-01

如何用element-ui的el-menu组件动态实现多级菜单?

1)创建menuTree.vue组件

<!--menuTree.vue-->
<template>
  <div class="gtd-menu-tree">
    <template v-for="(item, index) in data">
      <el-submenu :key="index" v-if="item.children && item.children.length>0" :index="item.title">
        <template slot="title">
          <span class="menu-text">{{ item.title }}</span>
        </template>
        <Menu :data="item.children" />
      </el-submenu>
      <el-menu-item :key="index" :index="item.path" :disabled="!item.path" v-else>
        <span slot="title" @click="onSelect(item)" class="menu-text">{{ item.title }}</span>
      </el-menu-item>
    </template>
  </div>
</template>

<script>
export default {
  name: "Menu",
  props: {
    data: {
      type: Array,
      required: true,
      default: function () {
        return [];
      },
    },
  },
  methods: {
    onSelect(item) {
      if (this.$route.path && this.$route.path != item.path) {
        this.$router.push({ path: item.path });
      }
    },
  },
};
</script>

2)vue文件中引入menuTree组件

<el-menu class="gtd-menu" mode="horizontal" router :default-active="$route.path">
	<!--引入menuTree组件-->
  <Menu :data="menuData" />
</el-menu>

<script>
import Menu from './components/menuTree.vue'
export default {
	data() {
		return {
			menuData: [
				{
					title: '一级菜单1',
					path: 'https://blog.csdn.net/yihanzhi'
				},
				{
					title: '一级菜单2',
					path: 'https://blog.csdn.net/yihanzhi/article/details/108074292'
				}
			]
		}
	},
	components: {
    	Menu
  	},
}
</script>
 类似资料: