vue实现展开与收起
Vue 实现展开与收起功能
在 Vue 中实现展开与收起功能可以通过多种方式完成,以下是一些常见的方法:
使用 v-show 或 v-if 控制显示
通过 Vue 的指令 v-show 或 v-if 可以动态控制元素的显示与隐藏。v-show 通过 CSS 的 display 属性切换,而 v-if 会直接移除或添加 DOM 节点。

<template>
<div>
<button @click="toggleContent">
{{ isExpanded ? '收起' : '展开' }}
</button>
<div v-show="isExpanded">
这里是需要展开与收起的内容。
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
};
},
methods: {
toggleContent() {
this.isExpanded = !this.isExpanded;
},
},
};
</script>
使用 CSS 过渡效果
如果需要平滑的展开与收起动画,可以结合 Vue 的 <transition> 组件和 CSS 过渡效果。

<template>
<div>
<button @click="toggleContent">
{{ isExpanded ? '收起' : '展开' }}
</button>
<transition name="slide">
<div v-show="isExpanded" class="content">
这里是需要展开与收起的内容。
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
};
},
methods: {
toggleContent() {
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="toggleContent">
{{ 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: {
toggleContent() {
this.isExpanded = !this.isExpanded;
},
},
};
</script>
<style>
.content {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
使用第三方库
如果需要更复杂的效果,可以借助第三方库如 vue-collapse 或 vue-animate-height。
<template>
<div>
<button @click="toggleContent">
{{ 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: {
toggleContent() {
this.isExpanded = !this.isExpanded;
},
},
};
</script>
以上方法可以根据具体需求选择使用,灵活实现展开与收起功能。






