vue实现展开动画
使用 Vue 的 Transition 组件实现展开动画
Vue 提供了内置的 Transition 组件,可以方便地实现元素的展开和折叠动画。以下是一个基本示例:
<template>
<div>
<button @click="isExpanded = !isExpanded">Toggle</button>
<Transition name="expand">
<div v-if="isExpanded" class="content">
This is the content that will expand and collapse
</div>
</Transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
}
}
</script>
<style>
.expand-enter-active,
.expand-leave-active {
transition: height 0.5s ease;
overflow: hidden;
}
.expand-enter-from,
.expand-leave-to {
height: 0;
}
.expand-enter-to,
.expand-leave-from {
height: 100px; /* 设置为内容实际高度或使用auto */
}
</style>
动态高度展开动画
当内容高度不确定时,可以使用 JavaScript 计算高度:
<template>
<div>
<button @click="toggle">Toggle</button>
<Transition
@before-enter="beforeEnter"
@enter="enter"
@after-enter="afterEnter"
@before-leave="beforeLeave"
@leave="leave"
>
<div v-if="isExpanded" class="content" ref="content">
Dynamic content height<br>
More lines<br>
Even more lines
</div>
</Transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
},
beforeEnter(el) {
el.style.height = '0'
},
enter(el) {
el.style.height = `${el.scrollHeight}px`
},
afterEnter(el) {
el.style.height = 'auto'
},
beforeLeave(el) {
el.style.height = `${el.scrollHeight}px`
},
leave(el) {
setTimeout(() => {
el.style.height = '0'
})
}
}
}
</script>
<style>
.content {
transition: height 0.5s ease;
overflow: hidden;
}
</style>
使用 CSS Grid 实现展开动画
CSS Grid 也可以实现平滑的展开效果:
<template>
<div class="grid-container">
<button @click="isExpanded = !isExpanded">Toggle</button>
<div class="grid-item" :class="{ expanded: isExpanded }">
Content that expands
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
}
}
</script>
<style>
.grid-container {
display: grid;
grid-template-rows: auto 0fr;
transition: grid-template-rows 0.5s ease;
}
.grid-item {
overflow: hidden;
}
.expanded {
grid-template-rows: auto 1fr;
}
</style>
使用第三方库(如 VueUse)
VueUse 提供了 useTransition 组合式 API 来实现更复杂的动画:
<template>
<div>
<button @click="isExpanded = !isExpanded">Toggle</button>
<div :style="style">
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 height = useTransition(isExpanded, {
duration: 500,
transition: [0.75, 0, 0.25, 1]
})
const style = computed(() => ({
height: `${height.value * 100}px`,
overflow: 'hidden'
}))
return { isExpanded, style }
}
}
</script>
注意事项
- 确保动画元素有
overflow: hidden属性 - 对于动态内容,需要在动画前获取元素的实际高度
- 使用
requestAnimationFrame可以优化动画性能 - 考虑添加
will-change: height属性提升动画性能 - 移动端设备可能需要添加
-webkit-overflow-scrolling: touch







