vue实现伸缩列表
实现伸缩列表的基本思路
使用Vue实现伸缩列表的核心在于动态控制列表项的显示与隐藏。可以通过v-for渲染列表,结合v-show或v-if控制子项的展开状态,并利用CSS过渡效果提升交互体验。
基础实现方法
模板结构
<template>
<div class="expandable-list">
<div
v-for="(item, index) in listData"
:key="index"
class="list-item"
>
<div class="header" @click="toggleExpand(index)">
{{ item.title }}
<span class="arrow">{{ isExpanded(index) ? '↑' : '↓' }}</span>
</div>
<div class="content" v-show="expandedItems.includes(index)">
{{ item.content }}
</div>
</div>
</div>
</template>
脚本逻辑

<script>
export default {
data() {
return {
listData: [
{ title: 'Item 1', content: 'Content for item 1' },
{ title: 'Item 2', content: 'Content for item 2' }
],
expandedItems: []
}
},
methods: {
toggleExpand(index) {
const position = this.expandedItems.indexOf(index)
position === -1
? this.expandedItems.push(index)
: this.expandedItems.splice(position, 1)
},
isExpanded(index) {
return this.expandedItems.includes(index)
}
}
}
</script>
样式设计
<style scoped>
.list-item {
border: 1px solid #eee;
margin-bottom: 8px;
border-radius: 4px;
}
.header {
padding: 12px;
background: #f5f5f5;
cursor: pointer;
display: flex;
justify-content: space-between;
}
.content {
padding: 12px;
transition: all 0.3s ease;
}
.arrow {
margin-left: 8px;
}
</style>
进阶优化方案
使用组件化设计 将列表项拆分为独立组件,提高代码复用性:

<template>
<expandable-item
v-for="(item, index) in listData"
:key="index"
:item="item"
:is-expanded="expandedItems.includes(index)"
@toggle="toggleExpand(index)"
/>
</template>
添加动画效果 利用Vue的过渡组件实现平滑展开:
<transition name="slide">
<div class="content" v-show="isExpanded">
<slot></slot>
</div>
</transition>
.slide-enter-active, .slide-leave-active {
transition: max-height 0.3s ease;
}
.slide-enter, .slide-leave-to {
max-height: 0;
overflow: hidden;
}
.slide-enter-to, .slide-leave {
max-height: 500px;
}
性能优化建议
对于大型列表,使用v-show代替v-if可以减少DOM操作。考虑虚拟滚动技术处理超长列表,避免同时渲染大量隐藏内容。
第三方库方案
考虑使用现成组件库加速开发:
- Vuetify的
v-expansion-panels - Element UI的
el-collapse - Ant Design Vue的
a-collapse
这些组件提供开箱即用的伸缩面板功能,支持手风琴模式、自定义图标等高级特性。






