vue引入实现图片轮播
使用 vue-awesome-swiper 实现图片轮播
vue-awesome-swiper 是基于 Swiper 的 Vue 轮播组件,功能强大且易于使用。需要先安装依赖:
npm install swiper vue-awesome-swiper
在组件中引入并使用:

<template>
<swiper :options="swiperOption">
<swiper-slide v-for="(image, index) in images" :key="index">
<img :src="image" alt="">
</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 {
images: [
'image1.jpg',
'image2.jpg',
'image3.jpg'
],
swiperOption: {
pagination: {
el: '.swiper-pagination'
},
loop: true,
autoplay: {
delay: 3000
}
}
}
}
}
</script>
使用纯 Vue 实现简单轮播
如果项目需求简单,可以不依赖第三方库,用纯 Vue 实现:

<template>
<div class="carousel">
<div class="slides" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
<div v-for="(image, index) in images" :key="index" class="slide">
<img :src="image" alt="">
</div>
</div>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
images: ['image1.jpg', 'image2.jpg', 'image3.jpg'],
currentIndex: 0,
timer: null
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.images.length
},
startAutoPlay() {
this.timer = setInterval(this.next, 3000)
}
},
mounted() {
this.startAutoPlay()
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style>
.carousel {
overflow: hidden;
position: relative;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
flex: 0 0 100%;
}
</style>
使用 Element UI 的走马灯组件
如果项目中使用 Element UI,可以直接使用其 Carousel 组件:
<template>
<el-carousel :interval="3000" arrow="always">
<el-carousel-item v-for="(image, index) in images" :key="index">
<img :src="image" alt="">
</el-carousel-item>
</el-carousel>
</template>
<script>
export default {
data() {
return {
images: ['image1.jpg', 'image2.jpg', 'image3.jpg']
}
}
}
</script>
使用 Vuetify 的轮播组件
Vuetify 也提供了轮播组件 v-carousel:
<template>
<v-carousel cycle height="400" hide-delimiters>
<v-carousel-item v-for="(image, i) in images" :key="i">
<v-img :src="image" contain height="100%"></v-img>
</v-carousel-item>
</v-carousel>
</template>
<script>
export default {
data() {
return {
images: ['image1.jpg', 'image2.jpg', 'image3.jpg']
}
}
}
</script>
每种方法各有优缺点,vue-awesome-swiper 功能最全面但体积较大,纯 Vue 实现最轻量但功能有限,UI 框架的组件则取决于项目是否已使用该框架。根据项目需求选择最合适的方案。






