效果圖
實(shí)現(xiàn)方式是:通過(guò)給定的數(shù)據(jù)結(jié)構(gòu)層數(shù)來(lái)動(dòng)態(tài)生成多級(jí)菜單
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>
下面的方法可以實(shí)現(xiàn)重置菜單選項(xiàng)為默認(rèn)項(xiàng)(需求場(chǎng)景:左側(cè)菜單切換時(shí),上方菜單就要重置為默認(rèn)選項(xiàng))文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-856950.html
<el-menu
:key="menuKey"
:default-active="activeIndex"
class="el-menu-demo"
mode="horizontal"
@select="handleSelect"
background-color="#f8f8f9"
style="margin-left: 1px;"
>
<Childrenmenu v-for="menuItem in menuItems" :key="menuItem.value" :item="menuItem" />
</el-menu>
<script setup>
const menuKey = ref(0);
//監(jiān)聽(tīng)切換事件
watch(() => stationsStore.stationId, (newValue, oldValue) => {
menuKey.value += 1;
});
通過(guò)給el-menu添加:key="menuKey"實(shí)現(xiàn)。
實(shí)現(xiàn)原理::key=“menuKey” 是 Vue 中的一個(gè)特殊語(yǔ)法,用于控制組件的重新渲染。當(dāng)一個(gè)組件的 key 值發(fā)生變化時(shí),Vue 會(huì)認(rèn)為這是一個(gè)新的組件實(shí)例,會(huì)強(qiáng)制重新創(chuàng)建和渲染這個(gè)組件。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-856950.html
到了這里,關(guān)于vue3+elementui-plus實(shí)現(xiàn)無(wú)限遞歸菜單的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!