vue动画实现折叠
vue动画实现折叠
在Vue中实现折叠动画可以通过内置的<transition>组件或结合CSS动画完成。以下是几种常见方法:

使用CSS过渡和v-show
通过Vue的v-show指令控制元素显示/隐藏,配合CSS过渡效果实现平滑折叠。

<template>
<div>
<button @click="toggle">Toggle</button>
<transition name="slide">
<div v-show="isVisible" class="content">
Content to be folded
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false
}
},
methods: {
toggle() {
this.isVisible = !this.isVisible
}
}
}
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: max-height 0.5s ease;
overflow: hidden;
}
.slide-enter, .slide-leave-to {
max-height: 0;
}
.slide-enter-to, .slide-leave {
max-height: 1000px; /* 需大于实际内容高度 */
}
.content {
background: #f0f0f0;
}
</style>
使用动态样式绑定
通过动态计算高度实现更精确的折叠控制,适合内容高度不确定的情况。
<template>
<div>
<button @click="toggle">Toggle</button>
<div
class="content"
:style="{ height: isVisible ? contentHeight + 'px' : '0' }"
ref="content"
>
Content with dynamic height
</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false,
contentHeight: 0
}
},
mounted() {
this.contentHeight = this.$refs.content.scrollHeight
},
methods: {
toggle() {
this.isVisible = !this.isVisible
}
}
}
</script>
<style>
.content {
transition: height 0.3s ease;
overflow: hidden;
background: #f0f0f0;
}
</style>
使用第三方库(如Velocity.js)
对于复杂动画场景,可以集成第三方动画库实现更丰富的效果。
<template>
<div>
<button @click="toggle">Toggle</button>
<div ref="content" class="content">
Content with Velocity.js animation
</div>
</div>
</template>
<script>
import Velocity from 'velocity-animate'
export default {
data() {
return {
isVisible: false
}
},
methods: {
toggle() {
this.isVisible = !this.isVisible
Velocity(
this.$refs.content,
{ height: this.isVisible ? 'auto' : 0 },
{ duration: 500 }
)
}
}
}
</script>
<style>
.content {
overflow: hidden;
background: #f0f0f0;
}
</style>
注意事项
- 使用
max-height过渡时需设置足够大的值以容纳内容 - 动态高度方案需要在内容变化时重新计算高度
- 对于性能敏感场景,建议使用CSS硬件加速(如
transform) - 移动端开发需注意动画流畅性和兼容性






