vue 实现轮播
使用 Swiper 插件实现轮播
安装 Swiper 依赖
npm install swiper
引入 Swiper 样式和组件
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
模板部分
<swiper
:slides-per-view="3"
:space-between="50"
@swiper="onSwiper"
@slideChange="onSlideChange"
>
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide>
<swiper-slide>Slide 3</swiper-slide>
</swiper>
脚本部分
setup() {
const onSwiper = (swiper) => {
console.log(swiper)
}
const onSlideChange = () => {
console.log('slide change')
}
return {
onSwiper,
onSlideChange,
}
}
原生 Vue 实现简单轮播
数据定义
data() {
return {
currentIndex: 0,
slides: [
{ id: 1, content: 'Slide 1' },
{ id: 2, content: 'Slide 2' },
{ id: 3, content: 'Slide 3' }
]
}
}
模板结构

<div class="carousel">
<div class="slides" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
<div class="slide" v-for="slide in slides" :key="slide.id">
{{ slide.content }}
</div>
</div>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
切换方法
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length
}
}
样式部分
.carousel {
overflow: hidden;
position: relative;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
flex: 0 0 100%;
min-width: 100%;
}
自动轮播实现
添加自动轮播功能

data() {
return {
timer: null,
interval: 3000
}
},
mounted() {
this.startAutoPlay()
},
methods: {
startAutoPlay() {
this.timer = setInterval(() => {
this.next()
}, this.interval)
},
stopAutoPlay() {
clearInterval(this.timer)
}
}
添加鼠标悬停控制
<div class="carousel" @mouseenter="stopAutoPlay" @mouseleave="startAutoPlay">
添加指示器
模板添加指示器
<div class="indicators">
<span
v-for="(slide, index) in slides"
:key="'indicator-'+slide.id"
:class="{ active: currentIndex === index }"
@click="goToSlide(index)"
></span>
</div>
跳转方法
methods: {
goToSlide(index) {
this.currentIndex = index
}
}
指示器样式
.indicators {
display: flex;
justify-content: center;
margin-top: 10px;
}
.indicators span {
width: 12px;
height: 12px;
margin: 0 5px;
border-radius: 50%;
background: #ccc;
cursor: pointer;
}
.indicators span.active {
background: #333;
}






