vue实现纵向轮播
实现纵向轮播的基本思路
纵向轮播通常通过CSS动画或JavaScript控制元素的垂直位移实现。Vue中可以结合v-for指令动态渲染轮播项,利用transform或margin-top属性实现纵向滚动效果。
核心代码结构
<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>
</div>
</template>
关键实现步骤
-
数据准备 定义轮播数据数组和当前索引:
data() { return { items: [ { content: 'Slide 1' }, { content: 'Slide 2' }, { content: 'Slide 3' } ], currentIndex: 0, timer: null } } -
自动轮播逻辑 使用
setInterval实现自动切换:
mounted() { this.startAutoPlay() }, methods: { startAutoPlay() { this.timer = setInterval(() => { this.nextSlide() }, 3000) }, nextSlide() { this.currentIndex = (this.currentIndex + 1) % this.items.length } } -
样式控制 添加必要的CSS样式:
.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; }
完整组件示例
<template>
<div class="vertical-carousel">
<button @click="prevSlide">↑</button>
<div class="viewport">
<div class="slider" :style="sliderStyle">
<div v-for="(item, i) in slides" :key="i" class="slide">
<img v-if="item.img" :src="item.img">
<h3>{{ item.title }}</h3>
</div>
</div>
</div>
<button @click="nextSlide">↓</button>
</div>
</template>
<script>
export default {
props: {
slides: {
type: Array,
required: true
},
interval: {
type: Number,
default: 3000
}
},
data() {
return {
currentIndex: 0
}
},
computed: {
sliderStyle() {
return {
transform: `translateY(${-this.currentIndex * 100}%)`,
transition: 'transform 0.5s ease'
}
}
},
mounted() {
this.startAutoPlay()
},
methods: {
startAutoPlay() {
setInterval(this.nextSlide, this.interval)
},
nextSlide() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length
},
prevSlide() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length
}
}
}
</script>
<style scoped>
.vertical-carousel {
display: flex;
flex-direction: column;
align-items: center;
}
.viewport {
height: 400px;
overflow: hidden;
position: relative;
width: 100%;
}
.slider {
width: 100%;
}
.slide {
height: 400px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
</style>
扩展功能建议
-
添加指示器 在模板中添加指示器元素,通过
v-for渲染,绑定点击事件切换对应索引。
-
鼠标悬停暂停 添加
@mouseenter和@mouseleave事件控制定时器的启停。 -
无限循环优化 复制首尾元素实现视觉上的无限循环,切换时做特殊处理。
-
响应式设计 使用CSS媒体查询或JavaScript监听窗口大小变化,动态调整轮播尺寸。
性能优化提示
- 使用
will-change: transform提升动画性能 - 对于复杂内容轮播,考虑使用
<keep-alive>缓存组件 - 清除定时器时使用
beforeDestroy生命周期钩子






