vue实现轮训图
使用Swiper实现轮播图
安装Swiper依赖
npm install swiper vue-awesome-swiper --save
引入Swiper组件
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import 'swiper/css/pagination'
import 'swiper/css/navigation'
基本模板结构
<template>
<swiper
:slidesPerView="1"
:spaceBetween="30"
:loop="true"
:pagination="{
clickable: true,
}"
:navigation="true"
:autoplay="{
delay: 2500,
disableOnInteraction: false,
}"
class="mySwiper"
>
<swiper-slide v-for="(item, index) in slides" :key="index">
<img :src="item.image" />
</swiper-slide>
</swiper>
</template>
数据定义
data() {
return {
slides: [
{ image: require('@/assets/slide1.jpg') },
{ image: require('@/assets/slide2.jpg') },
{ image: require('@/assets/slide3.jpg') }
]
}
}
纯CSS实现轮播图
HTML结构

<div class="slider">
<div class="slides">
<div v-for="(item, index) in slides"
:key="index"
:class="['slide', { active: currentIndex === index }]">
<img :src="item.image" />
</div>
</div>
<div class="dots">
<span v-for="(item, index) in slides"
:key="index"
:class="{ active: currentIndex === index }"
@click="currentIndex = index"></span>
</div>
</div>
CSS样式
.slider {
position: relative;
width: 100%;
height: 400px;
overflow: hidden;
}
.slides {
display: flex;
width: 100%;
height: 100%;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
height: 100%;
position: relative;
opacity: 0;
transition: opacity 0.5s ease;
}
.slide.active {
opacity: 1;
}
.dots {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.dots span {
width: 12px;
height: 12px;
margin: 0 5px;
border-radius: 50%;
background: rgba(255,255,255,0.5);
cursor: pointer;
}
.dots span.active {
background: white;
}
JavaScript逻辑
data() {
return {
currentIndex: 0,
slides: [
{ image: require('@/assets/slide1.jpg') },
{ image: require('@/assets/slide2.jpg') },
{ image: require('@/assets/slide3.jpg') }
],
interval: null
}
},
mounted() {
this.startAutoPlay()
},
methods: {
startAutoPlay() {
this.interval = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.slides.length
}, 3000)
},
stopAutoPlay() {
clearInterval(this.interval)
}
},
beforeDestroy() {
this.stopAutoPlay()
}
响应式轮播图实现
添加响应式断点

const breakpoints = {
640: {
slidesPerView: 1
},
768: {
slidesPerView: 2
},
1024: {
slidesPerView: 3
}
}
在Swiper配置中添加
:breakpoints="breakpoints"
带缩略图的轮播图
添加缩略图Swiper
<swiper
@swiper="setThumbsSwiper"
:spaceBetween="10"
:slidesPerView="4"
:freeMode="true"
:watchSlidesProgress="true"
class="thumbSwiper"
>
<swiper-slide v-for="(item, index) in slides" :key="index">
<img :src="item.image" />
</swiper-slide>
</swiper>
JavaScript关联
methods: {
setThumbsSwiper(swiper) {
this.thumbsSwiper = swiper
}
}
主Swiper添加配置
:thumbs="{ swiper: thumbsSwiper }"






