vue实现展开收起
Vue 实现展开收起功能
使用 v-if 或 v-show 控制显示
通过 Vue 的指令 v-if 或 v-show 可以轻松实现内容的展开与收起。v-if 会动态添加或移除 DOM 元素,而 v-show 仅切换 CSS 的 display 属性。
<template>
<div>
<button @click="toggleContent">点击{{ isExpanded ? '收起' : '展开' }}</button>
<div v-if="isExpanded">这里是需要展开收起的内容</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggleContent() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
使用 CSS 过渡动画
结合 Vue 的 <transition> 组件,可以为展开收起添加平滑的过渡效果。
<template>
<div>
<button @click="toggleContent">点击{{ isExpanded ? '收起' : '展开' }}</button>
<transition name="fade">
<div v-if="isExpanded" class="content">这里是需要展开收起的内容</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggleContent() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s, max-height 0.5s;
max-height: 500px;
overflow: hidden;
}
.fade-enter, .fade-leave-to {
opacity: 0;
max-height: 0;
}
.content {
padding: 10px;
background: #f5f5f5;
}
</style>
动态计算高度实现动画
如果需要更精确的动画效果,可以通过动态计算内容高度并结合 CSS 实现。

<template>
<div>
<button @click="toggleContent">点击{{ isExpanded ? '收起' : '展开' }}</button>
<div
class="content"
:style="{ height: isExpanded ? contentHeight + 'px' : '0' }"
ref="content"
>
这里是需要展开收起的内容
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
contentHeight: 0
}
},
mounted() {
this.contentHeight = this.$refs.content.scrollHeight
},
methods: {
toggleContent() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
.content {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
使用第三方库(如 vue-collapse)
对于更复杂的需求,可以使用第三方库如 vue-collapse 来快速实现展开收起功能。
安装依赖:

npm install vue-collapse --save
示例代码:
<template>
<div>
<button @click="toggleContent">点击{{ isExpanded ? '收起' : '展开' }}</button>
<vue-collapse v-model="isExpanded">
<div class="content">这里是需要展开收起的内容</div>
</vue-collapse>
</div>
</template>
<script>
import { VueCollapse } from 'vue-collapse'
export default {
components: {
VueCollapse
},
data() {
return {
isExpanded: false
}
},
methods: {
toggleContent() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
多级展开收起
对于多级菜单或嵌套内容的展开收起,可以通过递归组件或嵌套数据实现。
<template>
<div>
<div v-for="item in items" :key="item.id">
<button @click="toggleItem(item)">{{ item.name }}</button>
<div v-if="item.expanded">
<div v-for="child in item.children" :key="child.id">{{ child.name }}</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{
id: 1,
name: '菜单1',
expanded: false,
children: [
{ id: 11, name: '子菜单1' },
{ id: 12, name: '子菜单2' }
]
},
{
id: 2,
name: '菜单2',
expanded: false,
children: [
{ id: 21, name: '子菜单1' },
{ id: 22, name: '子菜单2' }
]
}
]
}
},
methods: {
toggleItem(item) {
item.expanded = !item.expanded
}
}
}
</script>
通过以上方法,可以灵活实现 Vue 中的展开收起功能,满足不同场景的需求。






