vue实现上下轮播图
实现上下轮播图的基本思路
在Vue中实现上下轮播图,核心是利用动态数据绑定和CSS过渡效果。通过定时器控制当前显示的索引,结合Vue的响应式特性更新视图。
准备轮播数据
在Vue组件的data中定义轮播图数据列表和当前显示索引:
data() {
return {
slides: [
{ id: 1, content: "Slide 1" },
{ id: 2, content: "Slide 2" },
{ id: 3, content: "Slide 3" }
],
currentIndex: 0
}
}
模板结构设计
使用v-for渲染轮播项,通过动态class控制显示状态:

<div class="carousel-container">
<div
v-for="(slide, index) in slides"
:key="slide.id"
:class="['slide', { 'active': index === currentIndex }]"
>
{{ slide.content }}
</div>
</div>
CSS过渡效果
实现垂直滑动效果需要CSS配合:
.carousel-container {
position: relative;
height: 300px;
overflow: hidden;
}
.slide {
position: absolute;
width: 100%;
height: 100%;
transition: transform 0.5s ease;
transform: translateY(100%);
}
.slide.active {
transform: translateY(0);
}
自动轮播逻辑
在mounted生命周期中添加定时器:

mounted() {
this.startAutoPlay();
},
methods: {
startAutoPlay() {
this.interval = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.slides.length;
}, 3000);
},
stopAutoPlay() {
clearInterval(this.interval);
}
}
处理边界情况
在组件销毁时清除定时器:
beforeDestroy() {
this.stopAutoPlay();
}
完整组件示例
整合后的完整组件代码:
<template>
<div class="vertical-carousel">
<div class="carousel-container">
<div
v-for="(slide, index) in slides"
:key="slide.id"
:class="['slide', { 'active': index === currentIndex }]"
>
{{ slide.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
slides: [
{ id: 1, content: "Slide 1 Content" },
{ id: 2, content: "Slide 2 Content" },
{ id: 3, content: "Slide 3 Content" }
],
currentIndex: 0,
interval: null
}
},
mounted() {
this.startAutoPlay();
},
beforeDestroy() {
this.stopAutoPlay();
},
methods: {
startAutoPlay() {
this.interval = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.slides.length;
}, 3000);
},
stopAutoPlay() {
clearInterval(this.interval);
}
}
}
</script>
<style>
.vertical-carousel {
width: 100%;
max-width: 600px;
margin: 0 auto;
}
.carousel-container {
position: relative;
height: 300px;
overflow: hidden;
}
.slide {
position: absolute;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
background-color: #f0f0f0;
border: 1px solid #ddd;
transition: transform 0.5s ease;
transform: translateY(100%);
}
.slide.active {
transform: translateY(0);
}
</style>
扩展功能建议
- 添加导航按钮控制轮播
- 实现触摸滑动支持
- 添加过渡动画自定义选项
- 响应式设计适配不同屏幕尺寸






