<template>
<div class="new_menu">
<div v-for="(item, index) in items" :class="{ 'item_selected': selectedItem === index }"
class="new_menu_item"
:key="item.path"
:index="`${ index+1 }`"
v-show="index<menuMax"
@click="handleItemClick(item,index)">
<div style="height: 35%"><Icon v-if="item?.icon" :icon="item?.icon" :size="28" :class="`${prefixClsIcon}-wrapper__icon`" /></div>
<div class="new_menu_item_title">{{item.name}}</div>
</div>
<div v-if="menuMax<items.length" class="new_menu_item">
<a-dropdown>
<a class="ant-dropdown-link" @click.prevent style="display: flex;flex-direction: column;justify-content: flex-end;align-items: center;color: white">
<div style="height: 35%"><Icon icon="ant-design:down-outlined" :size="28" :class="`${prefixClsIcon}-wrapper__icon`" /></div>
<div style="font-size: 16px">更多</div>
</a>
<template #overlay>
<a-menu>
<template v-for="(item, coIndex) in items" :key="coIndex">
<a-menu-item v-if="coIndex>menuMax" @click="menuItemClick(item)">
{{item.name}}
</a-menu-item>
</template>
</a-menu>
</template>
</a-dropdown>
</div>
</div>
</template>
<script lang="ts">
import Icon from '/@/components/Icon/index';
import {defineComponent, ref,onMounted,onUnmounted } from 'vue';
import { Menu } from 'ant-design-vue';
function debounce(func, wait) {
let timeout;
return function() {
const context = this;
const args = arguments;
const later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
export default defineComponent({
name: 'BasicMenu',
components: {
Icon,
Menu
},
setup(){
const items=[
{name:"首页1",icon:""},
{name:"首页2",icon:""},
{name:"首页3",icon:""},
{name:"首页4",icon:""},
{name:"首页5",icon:""},
{name:"首页6",icon:""},
{name:"首页7",icon:""},
{name:"首页8",icon:""},
{name:"首页9",icon:""},
{name:"首页10",icon:""},
{name:"首页11",icon:""},
];
let selectedItem=ref(0);
const handleItemClick=(item,index)=>{
selectedItem.value=index;
};
const menuItemClick=(item)=>{
selectedItem.value=6;
};
let menuMax=ref(6);
// 监听窗口大小变化,调整菜单项的显示与隐藏(加上防抖)
const handleResize = debounce(() => {
const menuWidth = document.querySelector('.new_menu').offsetWidth;
let num = menuWidth/200;
menuMax.value=num;
}, 200);
// 在组件挂载时添加resize事件监听器
onMounted(() => {
window.addEventListener('resize', handleResize);
handleResize();
});
// 在组件卸载时移除resize事件监听器
onUnmounted(() => {
window.removeEventListener('resize', handleResize);
});
return {
items,
menuItemClick,
menuMax,
selectedItem,
handleItemClick
};
}
})
</script>
<style lang="less">
.new_menu{
width: 80%;
height: 100%;
display: flex;
list-style: none;
.new_menu_item{
display: flex;
flex-direction: column;
align-items: center;
height: 100px;
margin-left: 5px;
justify-content: center;
.new_menu_item_title{
font-weight: bold;font-size: 16px;height: 30%
}
}
.new_menu_item:hover{
cursor: pointer;
background-color: #093D64;
}
}
.item_selected{
background-color: #093D64;
}
</style>
vue3+ant-design实现头部导航栏,菜单随宽度变化而增减
于 2024-05-10 11:06:26 首次发布