vue中实现伸缩框
Vue 中实现伸缩框的方法
在 Vue 中实现伸缩框功能,可以通过以下几种方式完成:
使用 CSS Transition 或 Animation
通过 Vue 的 v-bind:class 或 v-bind:style 动态绑定样式,结合 CSS 的 transition 或 animation 实现平滑的伸缩效果。
<template>
<div>
<button @click="toggle">Toggle</button>
<div
class="expandable-box"
:style="{ height: isExpanded ? '200px' : '50px' }"
>
Content here
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
};
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded;
}
}
};
</script>
<style>
.expandable-box {
width: 200px;
background: #f0f0f0;
overflow: hidden;
transition: height 0.3s ease;
}
</style>
使用 Vue Transition 组件
Vue 提供了 <transition> 组件,可以更方便地实现进入/离开的动画效果。

<template>
<div>
<button @click="toggle">Toggle</button>
<transition name="slide">
<div v-if="isExpanded" class="expandable-box">
Content here
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
};
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded;
}
}
};
</script>
<style>
.expandable-box {
width: 200px;
height: 200px;
background: #f0f0f0;
}
.slide-enter-active, .slide-leave-active {
transition: height 0.3s ease;
overflow: hidden;
}
.slide-enter, .slide-leave-to {
height: 0;
}
</style>
使用第三方库(如 Vue-Collapse)
如果需要更复杂的功能,可以使用第三方库如 vue-collapse。
安装:

npm install vue-collapse
使用:
<template>
<div>
<button @click="toggle">Toggle</button>
<vue-collapse :show="isExpanded">
<div class="expandable-box">
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>
<style>
.expandable-box {
width: 200px;
background: #f0f0f0;
}
</style>
动态计算内容高度
如果需要根据内容动态调整高度,可以通过 JavaScript 计算内容高度并动态设置。
<template>
<div>
<button @click="toggle">Toggle</button>
<div
class="expandable-box"
:style="{ height: currentHeight + 'px' }"
ref="expandableBox"
>
<div ref="content">
Content here
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
currentHeight: 0
};
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded;
if (this.isExpanded) {
this.currentHeight = this.$refs.content.clientHeight;
} else {
this.currentHeight = 0;
}
}
}
};
</script>
<style>
.expandable-box {
width: 200px;
background: #f0f0f0;
overflow: hidden;
transition: height 0.3s ease;
}
</style>
以上方法可以根据需求选择适合的方式实现伸缩框功能。






