vue实现伸缩列表
Vue 实现伸缩列表的方法
使用 Vue 实现伸缩列表可以通过动态绑定样式或类名,结合过渡效果实现平滑的展开和收起动画。以下是几种常见实现方式:
动态绑定高度
通过 v-if 或 v-show 控制列表显示,结合 CSS 过渡实现动画效果:
<template>
<div>
<button @click="toggleList">切换列表</button>
<transition name="slide">
<ul v-show="isExpanded">
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
]
}
},
methods: {
toggleList() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: max-height 0.5s ease;
overflow: hidden;
}
.slide-enter, .slide-leave-to {
max-height: 0;
}
.slide-enter-to, .slide-leave {
max-height: 500px;
}
</style>
使用第三方组件
Vue 生态中有现成的可伸缩列表组件,如 vue-accordion:
npm install vue-accordion
<template>
<vue-accordion>
<vue-accordion-item v-for="item in items" :key="item.id">
<template v-slot:title>{{ item.title }}</template>
<template v-slot:content>{{ item.content }}</template>
</vue-accordion-item>
</vue-accordion>
</template>
<script>
import { VueAccordion, VueAccordionItem } from 'vue-accordion'
export default {
components: {
VueAccordion,
VueAccordionItem
},
data() {
return {
items: [
{ id: 1, title: '标题1', content: '内容1' }
]
}
}
}
</script>
动态计算内容高度
对于需要精确控制高度的场景,可以通过 ref 获取元素实际高度:
<template>
<div>
<button @click="toggle">展开/收起</button>
<div ref="content" :style="{ height: contentHeight }">
<p>列表内容...</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
contentHeight: '0px'
}
},
methods: {
toggle() {
if (this.isExpanded) {
this.contentHeight = '0px'
} else {
this.contentHeight = `${this.$refs.content.scrollHeight}px`
}
this.isExpanded = !this.isExpanded
}
}
}
</script>
<style>
div {
transition: height 0.3s ease;
overflow: hidden;
}
</style>
使用 CSS Grid 布局
CSS Grid 的 grid-template-rows 属性也可以实现平滑过渡:
<template>
<div class="expandable" :class="{ expanded: isExpanded }">
<div class="content">
<p>列表内容...</p>
</div>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '展开' }}
</button>
</div>
</template>
<style>
.expandable {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 0.3s ease;
}
.expandable.expanded {
grid-template-rows: 1fr;
}
.content {
overflow: hidden;
}
</style>
以上方法可以根据具体需求选择,动态高度方法适用于内容高度不固定的场景,CSS Grid 方法则更现代简洁。







