vue实现菜单缩放
Vue 实现菜单缩放功能
实现菜单缩放功能通常涉及动态调整菜单宽度、切换图标以及平滑过渡效果。以下是基于 Vue 3 的 Composition API 实现方案:
核心逻辑与代码实现
模板部分
<template>
<div class="menu-container" :style="{ width: isCollapsed ? '64px' : '200px' }">
<button @click="toggleCollapse">
{{ isCollapsed ? '>' : '<' }}
</button>
<nav class="menu-list">
<router-link v-for="item in menuItems" :key="item.path" :to="item.path">
<span v-show="!isCollapsed">{{ item.title }}</span>
<component :is="item.icon" v-show="isCollapsed" />
</router-link>
</nav>
</div>
</template>
脚本部分
import { ref } from 'vue';
import { MenuIcon, HomeIcon, SettingsIcon } from '@heroicons/vue/outline';
export default {
setup() {
const isCollapsed = ref(false);
const menuItems = [
{ path: '/', title: '首页', icon: HomeIcon },
{ path: '/settings', title: '设置', icon: SettingsIcon }
];
const toggleCollapse = () => {
isCollapsed.value = !isCollapsed.value;
};
return { isCollapsed, menuItems, toggleCollapse };
}
};
样式部分

.menu-container {
transition: width 0.3s ease;
overflow: hidden;
height: 100vh;
background: #2c3e50;
color: white;
}
.menu-list {
display: flex;
flex-direction: column;
padding: 10px;
}
.menu-list a {
padding: 12px;
display: flex;
align-items: center;
color: white;
text-decoration: none;
border-radius: 4px;
margin-bottom: 5px;
}
.menu-list a:hover {
background: rgba(255,255,255,0.1);
}
button {
background: none;
border: none;
color: white;
padding: 15px;
cursor: pointer;
font-size: 16px;
}
进阶实现方案
添加动画效果
.menu-list a {
transition: all 0.3s ease;
}
.menu-list a span {
margin-left: 10px;
opacity: 1;
transition: opacity 0.3s ease;
}
.is-collapsed span {
opacity: 0;
width: 0;
}
使用 Vue Transition
<transition name="fade">
<span v-if="!isCollapsed">{{ item.title }}</span>
</transition>
响应式处理

import { onMounted, onUnmounted } from 'vue';
export default {
setup() {
const checkScreenSize = () => {
isCollapsed.value = window.innerWidth < 768;
};
onMounted(() => {
window.addEventListener('resize', checkScreenSize);
checkScreenSize();
});
onUnmounted(() => {
window.removeEventListener('resize', checkScreenSize);
});
}
};
状态管理方案
对于大型应用,建议使用 Pinia 管理菜单状态:
// stores/menu.js
import { defineStore } from 'pinia';
export const useMenuStore = defineStore('menu', {
state: () => ({
isCollapsed: false
}),
actions: {
toggleCollapse() {
this.isCollapsed = !this.isCollapsed;
}
}
});
性能优化建议
-
使用 CSS will-change 属性提升动画性能:
.menu-container { will-change: width; } -
对于复杂菜单,考虑虚拟滚动:
<RecycleScroller class="menu-list" :items="menuItems" :item-size="50" key-field="path" v-slot="{ item }"> <!-- 菜单项内容 --> </RecycleScroller>
实现时需根据具体需求调整过渡时间、断点阈值等参数,确保在不同设备和交互场景下都能提供良好的用户体验。






