vue实现展开与收起
Vue 实现展开与收起功能
使用 v-show 指令
通过 v-show 控制元素的显示与隐藏,结合按钮切换状态:
<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>
使用 v-if 指令
与 v-show 类似,但 v-if 会完全销毁和重建 DOM 元素:

<template>
<div>
<button @click="toggle">{{ isExpanded ? '收起' : '展开' }}</button>
<div v-if="isExpanded">需要展开/收起的内容</div>
</div>
</template>
动态高度过渡动画
结合 CSS 过渡实现平滑动画效果:

<template>
<div>
<button @click="toggle">{{ isExpanded ? '收起' : '展开' }}</button>
<div class="content" :style="{ height: isExpanded ? 'auto' : '0' }">
<div class="inner">需要展开/收起的内容</div>
</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;
}
.inner {
padding: 10px;
}
</style>
使用第三方组件
如 vue-collapse 等现成组件:
<template>
<div>
<button @click="toggle">{{ isExpanded ? '收起' : '展开' }}</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>
多级展开与收起
适用于嵌套结构的展开/收起:
<template>
<div>
<div v-for="item in items" :key="item.id">
<button @click="toggle(item)">{{ item.expanded ? '收起' : '展开' }}</button>
<div v-show="item.expanded">{{ item.content }}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: '内容1', expanded: false },
{ id: 2, content: '内容2', expanded: false }
]
}
},
methods: {
toggle(item) {
item.expanded = !item.expanded
}
}
}
</script>
注意事项
v-show只是切换display属性,适合频繁切换的场景v-if会完全销毁和重建 DOM,适合不频繁切换的场景- 过渡动画需要配合 CSS 的
transition属性实现 - 动态高度计算时可能需要获取元素的实际高度
- 多级展开时注意数据结构的合理设计






