vue实现收起展开面板
Vue 实现收起展开面板
使用 v-show 或 v-if 控制显示
通过 v-show 或 v-if 指令动态控制面板内容的显示与隐藏。v-show 通过 CSS 的 display 属性切换,适合频繁切换的场景;v-if 会销毁和重建 DOM 节点,适合不频繁切换的场景。
<template>
<div>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '展开' }}
</button>
<div v-show="isExpanded">
面板内容
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
}
}
</script>
添加过渡动画
使用 Vue 的 <transition> 组件为收起展开添加平滑的过渡效果。通过 CSS 定义过渡动画的进入和离开过程。

<template>
<div>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '展开' }}
</button>
<transition name="fade">
<div v-show="isExpanded" class="panel-content">
面板内容
</div>
</transition>
</div>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s, max-height 0.3s;
overflow: hidden;
}
.fade-enter, .fade-leave-to {
opacity: 0;
max-height: 0;
}
.panel-content {
max-height: 500px; /* 根据实际内容调整 */
}
</style>
使用第三方组件库
如果需要更复杂的功能(如手风琴效果),可以直接使用第三方 UI 库提供的组件,例如 Element UI 的 el-collapse 或 Ant Design Vue 的 a-collapse。
以 Element UI 为例:

<template>
<el-collapse v-model="activePanel">
<el-collapse-item title="面板标题" name="1">
面板内容
</el-collapse-item>
</el-collapse>
</template>
<script>
export default {
data() {
return {
activePanel: ['1'] // 默认展开的面板
}
}
}
</script>
动态内容与插槽
通过插槽(slot)实现面板内容的动态渲染,增强组件的复用性。
<template>
<div>
<button @click="toggle">
{{ isExpanded ? '收起' : '展开' }}
</button>
<transition name="slide">
<div v-show="isExpanded">
<slot></slot>
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
调用时:
<my-panel>
<p>自定义面板内容</p>
</my-panel>
注意事项
- 如果面板内容高度不确定,建议使用
max-height替代固定高度以实现平滑动画。 - 频繁切换时优先选择
v-show以减少性能开销。 - 过渡动画的 CSS 属性需与面板布局匹配(如
opacity或transform)。






