vue实现展开收拢
Vue 实现展开/收拢功能
展开/收拢功能通常用于显示或隐藏内容,可以通过 Vue 的条件渲染、动态样式或第三方库实现。以下是几种常见方法:
方法一:使用 v-if 或 v-show 控制显示
通过按钮切换布尔值,动态控制内容显示或隐藏。v-if 会完全移除 DOM 元素,而 v-show 仅切换 display: none。
<template>
<div>
<button @click="toggle">展开/收拢</button>
<div v-show="isExpanded">这里是需要展开/收拢的内容</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
方法二:动态绑定高度实现动画
结合 CSS 过渡效果,通过动态修改元素高度实现平滑的展开/收拢动画。
<template>
<div>
<button @click="toggle">展开/收拢</button>
<div
class="content"
:style="{ height: isExpanded ? 'auto' : '0px' }"
>
这里是需要展开/收拢的内容
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
.content {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
方法三:使用 Vue Transition 组件
通过 Vue 内置的 <transition> 组件实现更复杂的动画效果。
<template>
<div>
<button @click="toggle">展开/收拢</button>
<transition name="slide">
<div v-show="isExpanded" class="content">
这里是需要展开/收拢的内容
</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.5s ease;
}
.slide-enter-from, .slide-leave-to {
max-height: 0;
}
.slide-enter-to, .slide-leave-from {
max-height: 1000px;
}
.content {
overflow: hidden;
}
</style>
方法四:使用第三方库(如 vue-collapse)
对于更复杂的需求,可以使用专门处理展开/收拢的库。
安装:
npm install vue-collapse
示例:
<template>
<div>
<button @click="toggle">展开/收拢</button>
<vue-collapse v-model="isExpanded">
<div>这里是需要展开/收拢的内容</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>
注意事项
- 如果内容高度不确定,建议使用
max-height替代height,避免动画不流畅。 - 使用
v-show时,元素始终存在于 DOM 中,只是隐藏显示;v-if会完全移除元素。 - 对于性能敏感场景,优先考虑
v-show,避免频繁的 DOM 操作。







