vue 实现展开收起
Vue 实现展开收起功能
使用 v-show 或 v-if 控制显示
通过 Vue 的指令 v-show 或 v-if 可以轻松实现展开收起效果。v-show 通过 CSS 的 display 属性控制元素显示,适合频繁切换的场景;v-if 会销毁和重建 DOM 节点,适合条件较少变化的场景。
<template>
<div>
<button @click="toggle">{{ isExpanded ? '收起' : '展开' }}</button>
<div v-show="isExpanded">需要展开收起的内容</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
使用 CSS 过渡动画
如果需要平滑的展开收起动画效果,可以结合 Vue 的 <transition> 组件和 CSS 过渡属性。
<template>
<div>
<button @click="toggle">{{ isExpanded ? '收起' : '展开' }}</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, .slide-leave-to {
max-height: 0;
overflow: hidden;
}
.slide-enter-to, .slide-leave {
max-height: 1000px;
}
.content {
overflow: hidden;
}
</style>
动态计算高度
对于不确定高度的内容,可以通过动态计算高度实现更精确的动画效果。
<template>
<div>
<button @click="toggle">{{ isExpanded ? '收起' : '展开' }}</button>
<div ref="content" :style="{ height: isExpanded ? contentHeight + 'px' : '0' }" class="content">
需要展开收起的内容
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
contentHeight: 0
}
},
mounted() {
this.contentHeight = this.$refs.content.scrollHeight
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
.content {
overflow: hidden;
transition: height 0.5s ease;
}
</style>
使用第三方库
如果需要更复杂的展开收起效果,可以考虑使用第三方库如 vue-collapse 或 vue-slide-up-down。
安装 vue-slide-up-down:
npm install vue-slide-up-down
使用示例:
<template>
<div>
<button @click="toggle">{{ isExpanded ? '收起' : '展开' }}</button>
<slide-up-down :active="isExpanded">
需要展开收起的内容
</slide-up-down>
</div>
</template>
<script>
import SlideUpDown from 'vue-slide-up-down'
export default {
components: { SlideUpDown },
data() {
return {
isExpanded: false
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
多级展开收起
对于多级展开收起,可以通过嵌套组件或递归组件实现。

<template>
<div>
<div v-for="(item, index) in items" :key="index">
<button @click="toggle(index)">{{ item.expanded ? '收起' : '展开' }}</button>
<div v-show="item.expanded">{{ item.content }}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ expanded: false, content: '内容1' },
{ expanded: false, content: '内容2' }
]
}
},
methods: {
toggle(index) {
this.items[index].expanded = !this.items[index].expanded
}
}
}
</script>






