vue项目实现图片轮播
使用Swiper插件实现图片轮播
安装Swiper及相关依赖
npm install swiper vue-awesome-swiper
在Vue组件中引入
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import 'swiper/css/pagination'
import 'swiper/css/navigation'
基本模板结构
<template>
<swiper
:slides-per-view="3"
:space-between="30"
:pagination="{
clickable: true,
}"
:navigation="true"
class="mySwiper"
>
<swiper-slide v-for="(image, index) in images" :key="index">
<img :src="image.url" :alt="image.alt">
</swiper-slide>
</swiper>
</template>
组件脚本部分

<script>
export default {
data() {
return {
images: [
{ url: '/path/to/image1.jpg', alt: '描述1' },
{ url: '/path/to/image2.jpg', alt: '描述2' },
{ url: '/path/to/image3.jpg', alt: '描述3' }
]
}
}
}
</script>
自定义轮播样式
添加基础样式
<style scoped>
.swiper {
width: 100%;
height: 300px;
}
.swiper-slide {
display: flex;
justify-content: center;
align-items: center;
}
.swiper-slide img {
max-width: 100%;
max-height: 100%;
object-fit: cover;
}
</style>
配置轮播参数
常用配置选项
const swiperOptions = {
loop: true, // 循环播放
autoplay: {
delay: 2500, // 自动播放间隔
disableOnInteraction: false
},
effect: 'fade', // 切换效果
speed: 800, // 切换速度
breakpoints: { // 响应式配置
640: { slidesPerView: 2 },
768: { slidesPerView: 3 },
1024: { slidesPerView: 4 }
}
}
手动控制轮播
添加控制方法

methods: {
onSwiper(swiper) {
this.swiperInstance = swiper
},
nextSlide() {
this.swiperInstance.slideNext()
},
prevSlide() {
this.swiperInstance.slidePrev()
}
}
模板中添加控制按钮
<button @click="prevSlide">上一张</button>
<button @click="nextSlide">下一张</button>
实现缩略图功能
配置缩略图
const swiperOptions = {
thumbs: {
swiper: {
el: '.thumb-swiper',
slidesPerView: 4,
spaceBetween: 10
}
}
}
添加缩略图容器
<swiper class="thumb-swiper">
<swiper-slide v-for="(image, index) in images" :key="'thumb-'+index">
<img :src="image.thumbnail" :alt="'缩略图'+index">
</swiper-slide>
</swiper>






