vue实现折叠
Vue 实现折叠功能
在 Vue 中实现折叠功能可以通过多种方式完成,以下介绍几种常见的方法。
使用 v-show 或 v-if 控制显示隐藏
通过 Vue 的指令 v-show 或 v-if 可以轻松实现折叠效果。v-show 通过 CSS 的 display 属性切换显示隐藏,而 v-if 会动态添加或移除 DOM 元素。

<template>
<div>
<button @click="toggleCollapse">Toggle Collapse</button>
<div v-show="isCollapsed">
This content can be collapsed or expanded.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isCollapsed: true
}
},
methods: {
toggleCollapse() {
this.isCollapsed = !this.isCollapsed
}
}
}
</script>
使用 CSS Transition 添加动画效果
如果需要更平滑的折叠动画效果,可以结合 CSS Transition 或 Animation 实现。
<template>
<div>
<button @click="toggleCollapse">Toggle with Animation</button>
<transition name="slide">
<div v-show="isCollapsed" class="content">
This content has a smooth collapse animation.
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isCollapsed: true
}
},
methods: {
toggleCollapse() {
this.isCollapsed = !this.isCollapsed
}
}
}
</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 {
overflow: hidden;
}
</style>
使用第三方组件库
许多 Vue 组件库(如 Element UI、Ant Design Vue、Vuetify 等)提供了现成的折叠面板组件,可以直接使用。

以 Element UI 的 el-collapse 为例:
<template>
<el-collapse v-model="activeNames">
<el-collapse-item title="Section 1" name="1">
Content for section 1
</el-collapse-item>
<el-collapse-item title="Section 2" name="2">
Content for section 2
</el-collapse-item>
</el-collapse>
</template>
<script>
export default {
data() {
return {
activeNames: ['1']
}
}
}
</script>
动态高度折叠
如果需要更精确地控制折叠高度,可以通过动态计算内容高度并绑定样式实现。
<template>
<div>
<button @click="toggleCollapse">Toggle Dynamic Height</button>
<div
class="dynamic-content"
:style="{ height: isCollapsed ? contentHeight + 'px' : '0' }"
ref="content"
>
Dynamic height content goes here.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isCollapsed: false,
contentHeight: 0
}
},
mounted() {
this.contentHeight = this.$refs.content.scrollHeight
},
methods: {
toggleCollapse() {
this.isCollapsed = !this.isCollapsed
}
}
}
</script>
<style>
.dynamic-content {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
以上方法可以根据具体需求选择使用,简单的显示隐藏用 v-show 或 v-if 即可,需要动画效果则结合 CSS Transition,更复杂的场景可以考虑使用第三方组件库或动态高度实现。






