vue实现上下轮播图
Vue 实现上下轮播图
核心思路
通过动态绑定样式和监听事件实现垂直方向的轮播效果。利用 Vue 的响应式特性控制轮播图的当前索引,结合 CSS 过渡动画实现平滑切换。
基础实现步骤
模板部分

<template>
<div class="carousel-container">
<div class="carousel-track" :style="{ transform: `translateY(${-currentIndex * 100}%)` }">
<div class="carousel-item" v-for="(item, index) in items" :key="index">
{{ item.content }}
</div>
</div>
<button @click="prev">上移</button>
<button @click="next">下移</button>
</div>
</template>
脚本部分
<script>
export default {
data() {
return {
currentIndex: 0,
items: [
{ content: '内容1' },
{ content: '内容2' },
{ content: '内容3' }
]
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.items.length
}
}
}
</script>
样式部分

<style>
.carousel-container {
height: 300px;
overflow: hidden;
position: relative;
}
.carousel-track {
transition: transform 0.5s ease;
}
.carousel-item {
height: 300px;
display: flex;
align-items: center;
justify-content: center;
}
</style>
自动轮播实现
在组件中添加生命周期钩子实现自动轮播:
mounted() {
this.autoPlay = setInterval(() => {
this.next()
}, 3000)
},
beforeDestroy() {
clearInterval(this.autoPlay)
}
优化版本(支持无限循环)
修改切换逻辑实现无缝循环:
methods: {
next() {
if (this.currentIndex === this.items.length - 1) {
this.currentIndex = 0
} else {
this.currentIndex++
}
},
prev() {
if (this.currentIndex === 0) {
this.currentIndex = this.items.length - 1
} else {
this.currentIndex--
}
}
}
注意事项
- 确保容器高度与子项高度一致
- 过渡时间可根据需求调整
- 移动端需添加 touch 事件支持
- 大量图片时考虑懒加载优化性能






