vue实现展开收起
Vue 实现展开收起功能
展开收起功能可以通过 Vue 的 v-show、v-if 或动态样式来实现。以下是几种常见方法:
使用 v-show 控制显示隐藏
通过 v-show 绑定布尔值来控制元素的显示与隐藏。v-show 通过 CSS 的 display 属性切换,适合频繁切换的场景。

<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-if 会直接销毁或重建 DOM 元素,适合不频繁切换的场景,可以节省初始渲染资源。
<template>
<div>
<button @click="toggle">点击{{ isExpanded ? '收起' : '展开' }}</button>
<div v-if="isExpanded">这里是需要展开收起的内容</div>
</div>
</template>
结合 CSS 过渡动画
通过 Vue 的 <transition> 组件实现平滑的展开收起动画效果。

<template>
<div>
<button @click="toggle">点击{{ isExpanded ? '收起' : '展开' }}</button>
<transition name="fade">
<div v-show="isExpanded">这里是需要展开收起的内容</div>
</transition>
</div>
</template>
<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;
}
</style>
动态控制高度
通过动态绑定 style 或 class 实现高度变化,适合需要精确控制高度的场景。
<template>
<div>
<button @click="toggle">点击{{ isExpanded ? '收起' : '展开' }}</button>
<div
:style="{ maxHeight: isExpanded ? '500px' : '0' }"
class="content"
>
这里是需要展开收起的内容
</div>
</div>
</template>
<style>
.content {
overflow: hidden;
transition: max-height 0.3s ease;
}
</style>
使用第三方库
如果需要更复杂的动画效果,可以引入第三方库如 vue-animate 或 animate.css。
<template>
<div>
<button @click="toggle">点击{{ isExpanded ? '收起' : '展开' }}</button>
<div v-show="isExpanded" class="animate__animated animate__fadeIn">
这里是需要展开收起的内容
</div>
</div>
</template>
<script>
import 'animate.css'
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
以上方法可以根据实际需求选择,v-show 适合简单切换,v-if 适合条件渲染,结合过渡或动态样式可以实现更丰富的交互效果。






