vue实现面板收缩效果
使用 Vue 实现面板收缩效果
使用 v-show 指令
通过 v-show 控制面板的显示与隐藏,结合按钮切换状态。
<template>
<div>
<button @click="isCollapsed = !isCollapsed">
{{ isCollapsed ? '展开' : '折叠' }}
</button>
<div v-show="!isCollapsed">
面板内容
</div>
</div>
</template>
<script>
export default {
data() {
return {
isCollapsed: false
}
}
}
</script>
使用 transition 添加动画效果
结合 Vue 的 <transition> 组件实现平滑的展开/折叠动画。

<template>
<div>
<button @click="isCollapsed = !isCollapsed">
{{ isCollapsed ? '展开' : '折叠' }}
</button>
<transition name="slide">
<div v-show="!isCollapsed" class="panel">
面板内容
</div>
</transition>
</div>
</template>
<style>
.slide-enter-active, .slide-leave-active {
transition: max-height 0.5s ease;
}
.slide-enter, .slide-leave-to {
max-height: 0;
}
.slide-enter-to, .slide-leave {
max-height: 500px;
}
.panel {
overflow: hidden;
}
</style>
使用动态样式绑定
通过动态绑定 class 或 style 实现高度变化效果。

<template>
<div>
<button @click="togglePanel">切换面板</button>
<div
ref="panel"
:style="{ height: isCollapsed ? '0px' : panelHeight + 'px' }"
class="panel"
>
面板内容
</div>
</div>
</template>
<script>
export default {
data() {
return {
isCollapsed: false,
panelHeight: 0
}
},
mounted() {
this.panelHeight = this.$refs.panel.scrollHeight
},
methods: {
togglePanel() {
this.isCollapsed = !this.isCollapsed
}
}
}
</script>
<style>
.panel {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
使用第三方组件库
Element UI 或 Ant Design Vue 等库提供现成的折叠面板组件。
以 Element UI 为例:
<template>
<el-collapse>
<el-collapse-item title="面板标题">
面板内容
</el-collapse-item>
</el-collapse>
</template>
<script>
import { ElCollapse, ElCollapseItem } from 'element-plus'
export default {
components: {
ElCollapse,
ElCollapseItem
}
}
</script>
注意事项
- 使用
v-show会保留 DOM 元素,适合频繁切换的场景 - 使用
v-if会销毁和重建 DOM,适合不频繁切换的场景 - 动画效果需要处理好
overflow和max-height属性 - 动态内容变化后可能需要重新计算高度






