vue实现收缩展开
Vue 实现收缩展开功能
在 Vue 中实现收缩展开功能可以通过多种方式实现,常见的有使用 v-show、v-if 或结合 CSS 过渡动画。以下是几种实现方法:
使用 v-show 控制显示隐藏
v-show 通过切换 CSS 的 display 属性实现元素的显示和隐藏,适合频繁切换的场景。

<template>
<div>
<button @click="toggle">Toggle Content</button>
<div v-show="isExpanded">
This content can be expanded or collapsed.
</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">Toggle Content</button>
<div v-if="isExpanded">
This content can be expanded or collapsed.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
};
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded;
}
}
};
</script>
结合 CSS 过渡动画
通过 Vue 的 <transition> 组件实现平滑的展开和收缩动画效果。

<template>
<div>
<button @click="toggle">Toggle Content</button>
<transition name="slide">
<div v-show="isExpanded" class="content">
This content has a smooth transition effect.
</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: 100px;
}
</style>
动态高度动画
如果需要更精确的动画效果,可以通过 JavaScript 动态计算内容高度。
<template>
<div>
<button @click="toggle">Toggle Content</button>
<div ref="content" class="content" :style="{ height: contentHeight }">
This content has dynamic height animation.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
contentHeight: '0px'
};
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded;
if (this.isExpanded) {
this.contentHeight = `${this.$refs.content.scrollHeight}px`;
} else {
this.contentHeight = '0px';
}
}
}
};
</script>
<style>
.content {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
使用第三方库
如果需要更复杂的动画效果,可以结合第三方库如 vue-animate 或 animate.css。
<template>
<div>
<button @click="toggle">Toggle Content</button>
<transition
enter-active-class="animate__animated animate__fadeIn"
leave-active-class="animate__animated animate__fadeOut"
>
<div v-show="isExpanded" class="content">
This content uses Animate.css for animations.
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
};
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded;
}
}
};
</script>
<style>
@import 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css';
.content {
margin-top: 10px;
}
</style>
以上方法可以根据具体需求选择适合的实现方式。






