vue实现伸缩
Vue 实现伸缩功能的方法
在 Vue 中实现伸缩功能可以通过多种方式完成,常见的有使用 CSS 过渡、动态绑定类名、或结合第三方动画库(如 GSAP)。以下是几种实现方法:
使用 CSS 过渡和动态类名
通过 Vue 的 v-bind:class 动态切换类名,结合 CSS 的 transition 实现平滑伸缩效果。

<template>
<div>
<button @click="toggle">Toggle Expand</button>
<div class="expandable" :class="{ 'expanded': isExpanded }">
Content to expand or 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="toggle">Toggle Expand</button>
<transition name="expand">
<div v-if="isExpanded" class="content">
Content to expand or collapse
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
};
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded;
}
}
};
</script>
<style>
.expand-enter-active, .expand-leave-active {
transition: max-height 0.3s ease;
overflow: hidden;
}
.expand-enter, .expand-leave-to {
max-height: 0;
}
.expand-enter-to, .expand-leave {
max-height: 500px; /* 根据实际内容调整 */
}
</style>
使用第三方库(如 GSAP)
如果需要更复杂的动画效果,可以结合 GSAP(GreenSock Animation Platform)实现。
<template>
<div>
<button @click="toggle">Toggle Expand</button>
<div ref="expandable" class="expandable">
Content to expand or collapse
</div>
</div>
</template>
<script>
import { gsap } from "gsap";
export default {
data() {
return {
isExpanded: false
};
},
methods: {
toggle() {
if (this.isExpanded) {
gsap.to(this.$refs.expandable, { height: 0, duration: 0.3 });
} else {
gsap.to(this.$refs.expandable, { height: "auto", duration: 0.3 });
}
this.isExpanded = !this.isExpanded;
}
}
};
</script>
<style>
.expandable {
height: 0;
overflow: hidden;
}
</style>
动态计算高度
对于内容高度不确定的情况,可以通过 JavaScript 动态计算内容高度并设置。
<template>
<div>
<button @click="toggle">Toggle Expand</button>
<div ref="expandable" class="expandable" :style="{ height: currentHeight }">
Content to expand or collapse
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
currentHeight: "0px"
};
},
methods: {
toggle() {
if (this.isExpanded) {
this.currentHeight = "0px";
} else {
this.currentHeight = `${this.$refs.expandable.scrollHeight}px`;
}
this.isExpanded = !this.isExpanded;
}
}
};
</script>
<style>
.expandable {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
以上方法可以根据具体需求选择使用,CSS 过渡适合简单场景,而 GSAP 或动态高度计算适合更复杂的交互需求。






