vue 实现展开动画
Vue 实现展开动画的方法
使用 Vue Transition 组件
Vue 内置的 <transition> 组件可以方便地实现展开/折叠动画效果。通过设置 CSS 过渡或动画类名,控制元素高度的变化。

<template>
<div>
<button @click="isExpanded = !isExpanded">Toggle</button>
<transition name="expand">
<div v-show="isExpanded" class="content">
Content to be expanded
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
}
}
</script>
<style>
.expand-enter-active, .expand-leave-active {
transition: height 0.3s ease;
overflow: hidden;
}
.expand-enter, .expand-leave-to {
height: 0 !important;
}
</style>
动态计算高度
如果内容高度不确定,可以通过 JavaScript 动态获取高度并设置过渡效果。

<template>
<div>
<button @click="toggle">Toggle</button>
<div class="container" :style="{ height: currentHeight + 'px' }">
<div ref="content" class="content">
Content with dynamic height
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
currentHeight: 0
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
this.currentHeight = this.isExpanded ? this.$refs.content.scrollHeight : 0
}
}
}
</script>
<style>
.container {
transition: height 0.3s ease;
overflow: hidden;
}
</style>
使用第三方动画库
可以结合第三方动画库如 Animate.css 或 GSAP 实现更复杂的展开动画效果。
<template>
<div>
<button @click="isExpanded = !isExpanded">Toggle</button>
<transition
enter-active-class="animate__animated animate__fadeInDown"
leave-active-class="animate__animated animate__fadeOutUp"
>
<div v-show="isExpanded" class="content">
Content with Animate.css
</div>
</transition>
</div>
</template>
<script>
import 'animate.css'
export default {
data() {
return {
isExpanded: false
}
}
}
</script>
使用 Vue 插件
可以安装专门的 Vue 过渡插件如 vue-slide-up-down 或 vue-collapse 来简化实现。
npm install vue-slide-up-down
<template>
<div>
<button @click="isExpanded = !isExpanded">Toggle</button>
<slide-up-down v-model="isExpanded" :duration="300">
Content with vue-slide-up-down
</slide-up-down>
</div>
</template>
<script>
import SlideUpDown from 'vue-slide-up-down'
export default {
components: { SlideUpDown },
data() {
return {
isExpanded: false
}
}
}
</script>
每种方法都有其适用场景,可以根据项目需求选择最合适的实现方式。简单的展开动画使用 Vue Transition 组件即可,复杂动画可以考虑第三方库或插件。






