vue中实现伸缩框
实现伸缩框的基本思路
在Vue中实现伸缩框可以通过CSS过渡效果结合Vue的数据绑定和条件渲染完成。核心是利用v-show或v-if控制内容显示,通过CSS实现平滑的展开/收起动画。
使用CSS过渡实现基础伸缩
<template>
<div class="expandable-box">
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '展开' }}
</button>
<div class="content" :class="{ expanded: isExpanded }">
<!-- 内容区域 -->
这里是可伸缩的内容...
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
}
}
</script>
<style>
.content {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease-out;
}
.content.expanded {
max-height: 500px; /* 设置为足够大的值 */
}
</style>
动态计算内容高度
对于不确定高度的内容,可以通过ref获取DOM元素的实际高度:

<template>
<div class="expandable-box">
<button @click="toggleExpand">
{{ isExpanded ? '收起' : '展开' }}
</button>
<div ref="content" class="content" :style="{ height: contentHeight }">
<!-- 可变高度的内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
contentHeight: '0px'
}
},
methods: {
toggleExpand() {
if (!this.isExpanded) {
this.contentHeight = `${this.$refs.content.scrollHeight}px`
} else {
this.contentHeight = '0px'
}
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
.content {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
使用第三方组件库
对于更复杂的需求,可以使用现成的UI组件库:
-
Element UI的Collapse组件:

<el-collapse v-model="activeNames"> <el-collapse-item title="标题" name="1"> 内容区域 </el-collapse-item> </el-collapse> -
Ant Design Vue的Collapse组件:
<a-collapse v-model:activeKey="activeKey"> <a-collapse-panel key="1" header="标题"> 内容区域 </a-collapse-panel> </a-collapse>
高级动画效果
使用Vue的<transition>组件实现更丰富的动画:
<template>
<div>
<button @click="show = !show">切换</button>
<transition
name="expand"
@enter="enter"
@after-enter="afterEnter"
@leave="leave"
>
<div v-if="show" class="content">
动画过渡的内容...
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
},
methods: {
enter(el) {
el.style.height = 'auto'
const height = getComputedStyle(el).height
el.style.height = '0'
setTimeout(() => {
el.style.height = height
})
},
afterEnter(el) {
el.style.height = 'auto'
},
leave(el) {
el.style.height = getComputedStyle(el).height
setTimeout(() => {
el.style.height = '0'
})
}
}
}
</script>
<style>
.expand-enter-active, .expand-leave-active {
transition: height 0.3s ease;
overflow: hidden;
}
</style>
注意事项
- 使用
max-height过渡时需设置足够大的值确保内容完全展开 - 动态高度计算可能引发布局抖动,建议添加
overflow: hidden - 复杂场景考虑使用
requestAnimationFrame优化性能 - 移动端注意添加
-webkit-overflow-scrolling: touch保持滚动流畅






