vue实现走马灯
Vue实现走马灯(轮播图)的方法
使用原生Vue实现
通过Vue的v-for和动态绑定样式实现基础走马灯效果:
<template>
<div class="carousel">
<div
class="carousel-item"
v-for="(item, index) in items"
:key="index"
:style="{ transform: `translateX(${-currentIndex * 100}%)` }"
>
{{ item }}
</div>
<button @click="prev">上一张</button>
<button @click="next">下一张</button>
</div>
</template>
<script>
export default {
data() {
return {
items: ['内容1', '内容2', '内容3'],
currentIndex: 0,
timer: null
}
},
methods: {
next() {
this.currentIndex = (this.currentIndex + 1) % this.items.length
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length
},
startAutoPlay() {
this.timer = setInterval(this.next, 3000)
}
},
mounted() {
this.startAutoPlay()
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style>
.carousel {
position: relative;
overflow: hidden;
width: 100%;
height: 200px;
}
.carousel-item {
position: absolute;
width: 100%;
height: 100%;
transition: transform 0.5s ease;
}
</style>
使用第三方库(Swiper)
安装Swiper库:
npm install swiper
Vue组件实现:
<template>
<swiper
:modules="modules"
:slides-per-view="1"
:space-between="50"
:autoplay="{ delay: 2500 }"
@swiper="onSwiper"
>
<swiper-slide v-for="(slide, index) in slides" :key="index">
{{ slide }}
</swiper-slide>
</swiper>
</template>
<script>
import { Autoplay } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
export default {
components: {
Swiper,
SwiperSlide
},
setup() {
return {
modules: [Autoplay],
slides: ['Slide 1', 'Slide 2', 'Slide 3'],
onSwiper: (swiper) => console.log(swiper)
}
}
}
</script>
使用Element UI的Carousel组件
安装Element UI:
npm install element-plus
实现代码:
<template>
<el-carousel :interval="3000" type="card" height="200px">
<el-carousel-item v-for="item in 4" :key="item">
<h3>{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</template>
<script>
import { ElCarousel, ElCarouselItem } from 'element-plus'
export default {
components: {
ElCarousel,
ElCarouselItem
}
}
</script>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 18px;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
</style>
实现无限循环效果
在原生实现中修改next方法:
next() {
this.currentIndex++
if (this.currentIndex >= this.items.length) {
setTimeout(() => {
this.currentIndex = 0
}, 500) // 等待过渡动画完成
}
}
添加指示器
在模板中添加指示器元素:
<div class="indicators">
<span
v-for="(item, index) in items"
:key="index"
:class="{ active: currentIndex === index }"
@click="currentIndex = index"
></span>
</div>
样式添加:
.indicators {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
}
.indicators span {
display: inline-block;
width: 10px;
height: 10px;
margin: 0 5px;
border-radius: 50%;
background: #ccc;
cursor: pointer;
}
.indicators span.active {
background: #333;
}






