Vue.js侧边栏收缩时无法仅保留汉堡图标隐藏菜单栏问题
Vue侧边栏收缩状态菜单内容无法完全隐藏修复
问题场景
开发Vue侧边栏组件时,要求small-menu类生效的收缩状态下仅显示汉堡菜单图标,其余侧边栏内容全部隐藏,调整CSS后未达到预期效果。
效果参考:
原有实现代码
模板部分
<div class="menu" :class="{ 'small-menu': smallMenu }"> <MenuItem v-for="(item, index) in menuTree" :key="index" :data="item.children" :label="item.label" :depth="0" :smallMenu="smallMenu" /> <i @click="smallMenu = !smallMenu" class="material-icons">menu</i> </div>
样式部分
<style lang="scss" scoped> .menu { background: grey; position: fixed; height: 100vh; width: 240px; left: 110; top: 0; border-right: 1px solid #ececec; transition: all 0.3s ease; overflow: auto; padding-top: 50px; i { position: fixed; left: 250px; font-size: 20px; top: 15px; user-select: none; cursor: pointer; transition: all 0.3s ease; } &.small-menu { overflow: inherit; width: 60px; padding-top: 50px; i { left: 20px; } } } </style>
问题原因
- 收缩状态下设置
overflow: inherit,无法裁切超出60px宽度的菜单内容,溢出部分会直接展示在侧边栏外部 - 仅修改了侧边栏容器宽度,没有对内部
MenuItem组件做显隐控制 - 原有样式中
left: 110缺少长度单位,属于无效CSS属性
修复方案
- 给
left属性补充px单位,修正无效样式 - 将收缩状态下的
overflow: inherit改为overflow: hidden,裁切超出容器范围的内容 - 增加收缩状态下菜单项的隐藏规则,给汉堡按钮设置更高层级避免被遮挡
修复后样式
<style lang="scss" scoped> .menu { background: grey; position: fixed; height: 100vh; width: 240px; left: 110px; top: 0; border-right: 1px solid #ececec; transition: all 0.3s ease; overflow: auto; padding-top: 50px; i { position: fixed; left: 250px; font-size: 20px; top: 15px; user-select: none; cursor: pointer; transition: all 0.3s ease; z-index: 10; } &.small-menu { overflow: hidden; width: 60px; padding-top: 50px; /* 替换为实际MenuItem组件的根类名,scoped下用:deep穿透 */ :deep(.menu-item) { display: none; } i { left: 20px; } } } </style>
如果需要保留收缩状态下菜单项的DOM占位(比如实现悬浮展开子菜单的交互),把
display: none替换为visibility: hidden即可。
内容的提问来源于stack exchange,提问作者sam lim
相关产品推荐
相关产品推荐

