vue实现伸缩
Vue实现伸缩效果的方法
使用CSS过渡和Vue的v-show或v-if指令
在Vue中可以通过结合CSS过渡和v-show指令实现简单的伸缩效果。定义一个CSS类,利用transition属性控制动画效果,通过Vue的数据绑定动态切换类名。

<template>
<div>
<button @click="toggle">Toggle</button>
<div class="expandable" :class="{ 'expanded': isExpanded }">
Content to expand/collapse
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
.expandable {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease-out;
}
.expanded {
max-height: 500px;
}
</style>
使用Vue Transition组件
Vue的Transition组件提供了更丰富的动画控制能力。可以定义进入和离开的过渡效果,实现更平滑的伸缩动画。

<template>
<div>
<button @click="show = !show">Toggle</button>
<transition name="expand">
<div v-if="show" class="content">
Content with transition
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
<style>
.expand-enter-active, .expand-leave-active {
transition: all 0.3s ease;
overflow: hidden;
}
.expand-enter, .expand-leave-to {
max-height: 0;
padding-top: 0;
padding-bottom: 0;
}
.expand-enter-to, .expand-leave {
max-height: 100px;
padding-top: 10px;
padding-bottom: 10px;
}
</style>
使用第三方动画库
对于更复杂的伸缩效果,可以集成第三方动画库如Animate.css或GSAP。这些库提供了丰富的预定义动画,可以轻松实现各种伸缩效果。
<template>
<div>
<button @click="show = !show">Toggle</button>
<transition
enter-active-class="animate__animated animate__zoomIn"
leave-active-class="animate__animated animate__zoomOut"
>
<div v-if="show" class="content">
Content with Animate.css
</div>
</transition>
</div>
</template>
<script>
import 'animate.css'
export default {
data() {
return {
show: false
}
}
}
</script>
动态计算高度
对于内容高度不确定的情况,可以使用JavaScript动态计算内容高度,实现更精确的伸缩效果。
<template>
<div>
<button @click="toggle">Toggle</button>
<div ref="content" class="content" :style="{ height: contentHeight }">
Dynamic content
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
contentHeight: '0px'
}
},
methods: {
toggle() {
if (this.isExpanded) {
this.contentHeight = '0px'
} else {
this.contentHeight = `${this.$refs.content.scrollHeight}px`
}
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
.content {
overflow: hidden;
transition: height 0.3s ease;
}
</style>






