vue实现伸缩框
Vue 实现伸缩框的方法
使用 CSS Transition 和 v-show/v-if
通过 Vue 的指令结合 CSS 过渡效果实现伸缩动画。定义一个布尔值控制元素的显示隐藏,并添加 CSS 过渡属性。
<template>
<div>
<button @click="toggle">Toggle</button>
<div class="expandable" :class="{ 'expanded': isExpanded }">
Content here...
</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;
}
.expandable.expanded {
max-height: 500px; /* Adjust based on content */
}
</style>
使用 Vue Transition 组件
Vue 内置的 <transition> 组件可以更方便地实现动画效果。通过设置 CSS 类名和过渡属性控制伸缩效果。

<template>
<div>
<button @click="toggle">Toggle</button>
<transition name="slide">
<div v-show="isExpanded" class="content">
Content here...
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: max-height 0.3s ease;
}
.slide-enter, .slide-leave-to {
max-height: 0;
overflow: hidden;
}
.slide-enter-to, .slide-leave {
max-height: 500px;
}
</style>
动态计算高度
如果内容高度不确定,可以通过 JavaScript 动态计算内容高度并应用动画。
<template>
<div>
<button @click="toggle">Toggle</button>
<div class="expandable" :style="{ height: height }">
<div ref="content">
Content here...
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
height: '0px'
}
},
methods: {
toggle() {
if (this.isExpanded) {
this.height = '0px'
} else {
this.height = `${this.$refs.content.scrollHeight}px`
}
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
.expandable {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
使用第三方库(如 Vue-Collapse)
对于更复杂的需求,可以使用第三方库如 vue-collapse 快速实现伸缩功能。

安装:
npm install vue-collapse
使用:
<template>
<div>
<button @click="toggle">Toggle</button>
<vue-collapse :show="isExpanded">
<div class="content">
Content here...
</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>
以上方法可以根据具体需求选择,从简单的 CSS 过渡到动态高度计算或第三方库,灵活实现伸缩框效果。






