vue实现伸缩
Vue 实现伸缩效果的方法
使用 CSS Transition 和 v-show/v-if
在 Vue 中可以通过结合 CSS 过渡和 v-show 或 v-if 实现伸缩效果。定义一个带有 transition 的 CSS 类,并通过 Vue 的数据绑定控制元素的显示与隐藏。
<template>
<div>
<button @click="toggle">Toggle</button>
<transition name="slide">
<div v-show="isVisible" class="content">
This content can expand and collapse.
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false
};
},
methods: {
toggle() {
this.isVisible = !this.isVisible;
}
}
};
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: max-height 0.5s ease;
}
.slide-enter, .slide-leave-to {
max-height: 0;
overflow: hidden;
}
.slide-enter-to, .slide-leave {
max-height: 500px;
}
.content {
background: #f0f0f0;
padding: 10px;
}
</style>
使用动态绑定样式
通过动态绑定 style 或 class 实现高度变化,结合 Vue 的响应式数据控制伸缩效果。
<template>
<div>
<button @click="toggle">Toggle</button>
<div
class="content"
:style="{ height: isExpanded ? '200px' : '0px' }"
>
Content expands and collapses here.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
};
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded;
}
}
};
</script>
<style>
.content {
transition: height 0.3s ease;
overflow: hidden;
background: #f0f0f0;
padding: 10px;
}
</style>
使用第三方库(如 Vue-Collapse)
如果需要更复杂的功能,可以使用第三方库如 vue-collapse 实现伸缩效果。
安装依赖:
npm install vue-collapse --save
示例代码:

<template>
<div>
<button @click="toggle">Toggle</button>
<vue-collapse :show="isExpanded">
<div class="content">
This content collapses and expands smoothly.
</div>
</vue-collapse>
</div>
</template>
<script>
import VueCollapse from 'vue-collapse';
export default {
components: {
VueCollapse
},
data() {
return {
isExpanded: false
};
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded;
}
}
};
</script>
<style>
.content {
background: #f0f0f0;
padding: 10px;
}
</style>
注意事项
- 使用
max-height替代height可以避免内容高度不确定的问题。 - 确保设置
overflow: hidden以隐藏超出部分。 - 使用
transition实现平滑动画效果时,确保过渡属性与绑定的样式属性一致。






