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-from, .expand-leave-to {
height: 0;
}
.expand-enter-to, .expand-leave-from {
height: 100px; /* 设置内容实际高度 */
}
</style>
使用动态高度实现自动计算
当内容高度不确定时,可以使用 JavaScript 动态计算高度,实现更灵活的展开动画。

<template>
<div>
<button @click="toggleExpand">Toggle</button>
<div class="container">
<div ref="content" class="content" :style="{ height: currentHeight }">
<p>Dynamic content here...</p>
<p>Line 2</p>
<p>Line 3</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
currentHeight: '0px'
}
},
methods: {
toggleExpand() {
this.isExpanded = !this.isExpanded
if (this.isExpanded) {
this.currentHeight = `${this.$refs.content.scrollHeight}px`
} else {
this.currentHeight = '0px'
}
}
}
}
</script>
<style>
.container {
overflow: hidden;
transition: height 0.3s ease;
}
.content {
padding: 10px;
background: #f5f5f5;
}
</style>
使用第三方动画库(如 GSAP)
对于更复杂的动画效果,可以集成 GSAP 等专业动画库。
<template>
<div>
<button @click="toggleExpand">Toggle</button>
<div ref="content" class="content">
<p>Content with GSAP animation</p>
</div>
</div>
</template>
<script>
import gsap from 'gsap'
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggleExpand() {
this.isExpanded = !this.isExpanded
if (this.isExpanded) {
gsap.to(this.$refs.content, {
height: 'auto',
duration: 0.3,
ease: 'power2.out'
})
} else {
gsap.to(this.$refs.content, {
height: 0,
duration: 0.3,
ease: 'power2.in'
})
}
}
},
mounted() {
gsap.set(this.$refs.content, { height: 0 })
}
}
</script>
<style>
.content {
overflow: hidden;
}
</style>
使用 VueUse 的 useTransition 组合式 API
VueUse 库提供了更便捷的动画解决方案。
<template>
<div>
<button @click="isExpanded = !isExpanded">Toggle</button>
<div class="content" :style="{ height: `${height}px` }">
Content with VueUse transition
</div>
</div>
</template>
<script>
import { ref } from 'vue'
import { useTransition } from '@vueuse/core'
export default {
setup() {
const isExpanded = ref(false)
const source = ref(0)
const target = ref(100) // 目标高度
const height = useTransition(source, {
duration: 300,
transition: [0.25, 0.1, 0.25, 1] // CSS easing function
})
watch(isExpanded, (val) => {
source.value = val ? target.value : 0
})
return { isExpanded, height }
}
}
</script>
<style>
.content {
overflow: hidden;
background: #f5f5f5;
padding: 10px;
}
</style>
注意事项
- 确保动画元素设置了
overflow: hidden属性,防止内容溢出 - 对于性能优化,考虑使用
will-change: height属性 - 在移动设备上,添加
-webkit-overflow-scrolling: touch改善滚动体验 - 动画持续时间建议在 200-300ms 之间,以获得最佳用户体验






