vue项目实现图片轮播
使用 Vue 实现图片轮播
基于 vue-awesome-swiper 实现
安装依赖:
npm install swiper vue-awesome-swiper
组件代码示例:
<template>
<swiper :options="swiperOption">
<swiper-slide v-for="(item, index) in imgList" :key="index">
<img :src="item" class="swiper-img">
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
imgList: [
'image1.jpg',
'image2.jpg',
'image3.jpg'
],
swiperOption: {
pagination: {
el: '.swiper-pagination'
},
autoplay: {
delay: 3000,
disableOnInteraction: false
},
loop: true
}
}
}
}
</script>
<style>
.swiper-img {
width: 100%;
height: auto;
}
</style>
原生实现方案
基本轮播组件:
<template>
<div class="carousel">
<div class="slides" :style="slideStyle">
<div v-for="(img, index) in images" :key="index" class="slide">
<img :src="img" alt="">
</div>
</div>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
images: ['img1.jpg', 'img2.jpg', 'img3.jpg'],
currentIndex: 0,
timer: null
}
},
computed: {
slideStyle() {
return {
transform: `translateX(-${this.currentIndex * 100}%)`
}
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.images.length
},
autoPlay() {
this.timer = setInterval(this.next, 3000)
}
},
mounted() {
this.autoPlay()
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style>
.carousel {
position: relative;
overflow: hidden;
width: 100%;
height: 300px;
}
.slides {
display: flex;
transition: transform 0.5s ease;
height: 100%;
}
.slide {
flex: 0 0 100%;
height: 100%;
}
.slide img {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
实现功能增强
添加指示器:
<template>
<div class="indicators">
<span
v-for="(item, index) in imgList"
:key="index"
:class="{ active: currentIndex === index }"
@click="goTo(index)"
></span>
</div>
</template>
<script>
export default {
methods: {
goTo(index) {
this.currentIndex = index
}
}
}
</script>
<style>
.indicators span {
display: inline-block;
width: 10px;
height: 10px;
margin: 0 5px;
border-radius: 50%;
background: #ccc;
cursor: pointer;
}
.indicators span.active {
background: #333;
}
</style>
响应式处理
监听窗口变化:
mounted() {
window.addEventListener('resize', this.handleResize)
this.handleResize()
},
methods: {
handleResize() {
this.carouselWidth = this.$el.offsetWidth
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
}
性能优化
图片懒加载:
<img v-lazy="item" class="swiper-img">
需要安装并配置vue-lazyload:
npm install vue-lazyload
在main.js中:
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
loading: 'loading.gif',
attempt: 1
})






