vue实现收缩展开
Vue 实现收缩展开功能
在 Vue 中实现收缩展开功能可以通过多种方式实现,以下是几种常见的方法:
使用 v-show 或 v-if 控制显示隐藏
通过 Vue 的指令 v-show 或 v-if 可以轻松实现元素的显示和隐藏。v-show 通过 CSS 的 display 属性控制,v-if 则是直接移除或添加 DOM 节点。
<template>
<div>
<button @click="toggle">Toggle Content</button>
<div v-show="isVisible">
This content can be toggled.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false
}
},
methods: {
toggle() {
this.isVisible = !this.isVisible;
}
}
}
</script>
使用 CSS 过渡动画
如果需要平滑的展开和收缩效果,可以结合 Vue 的 <transition> 组件和 CSS 过渡。

<template>
<div>
<button @click="toggle">Toggle with Animation</button>
<transition name="slide">
<div v-show="isVisible" class="content">
This content slides in and out.
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false
}
},
methods: {
toggle() {
this.isVisible = !this.isVisible;
}
}
}
</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;
}
.content {
overflow: hidden;
}
</style>
动态绑定 class 实现高度变化
通过动态绑定 class 并结合 CSS 的 max-height 属性,可以实现更灵活的展开和收缩效果。
<template>
<div>
<button @click="toggle">Toggle Height</button>
<div :class="{ 'expanded': isExpanded, 'collapsed': !isExpanded }" class="content">
This content changes height dynamically.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded;
}
}
}
</script>
<style>
.content {
overflow: hidden;
transition: max-height 0.3s ease;
}
.collapsed {
max-height: 0;
}
.expanded {
max-height: 500px;
}
</style>
使用第三方库
如果需要更复杂的效果,可以借助第三方库如 vue-collapse 或 vue-accordion。

安装 vue-collapse:
npm install vue-collapse
使用示例:
<template>
<div>
<button @click="toggle">Toggle Collapse</button>
<vue-collapse :show="isCollapsed">
<div class="content">
This content is collapsed by default.
</div>
</vue-collapse>
</div>
</template>
<script>
import { VueCollapse } from 'vue-collapse';
export default {
components: {
VueCollapse
},
data() {
return {
isCollapsed: false
}
},
methods: {
toggle() {
this.isCollapsed = !this.isCollapsed;
}
}
}
</script>
列表的展开与收缩
对于列表的展开与收缩,可以通过动态渲染数组的子集来实现。
<template>
<div>
<button @click="toggleItems">Show More/Less</button>
<ul>
<li v-for="(item, index) in visibleItems" :key="index">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'],
showAll: false
}
},
computed: {
visibleItems() {
return this.showAll ? this.items : this.items.slice(0, 3);
}
},
methods: {
toggleItems() {
this.showAll = !this.showAll;
}
}
}
</script>
以上方法可以根据具体需求选择适合的方式实现收缩展开功能。






