vue实现京东轮播图
Vue 实现京东轮播图
使用 vue-awesome-swiper 插件
安装 vue-awesome-swiper 插件,该插件基于 Swiper.js,适合 Vue 项目中使用。
npm install swiper vue-awesome-swiper --save
在组件中引入并使用:

<template>
<swiper ref="mySwiper" :options="swiperOptions">
<swiper-slide v-for="(item, index) in banners" :key="index">
<img :src="item.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 {
banners: [
{ image: 'https://img10.360buyimg.com/babel/s800x360_jfs/t1/123258/21/5943/136401/5efbf328E8d5b78ef/3d2c7f9e7b7d9b3c.jpg' },
{ image: 'https://img10.360buyimg.com/babel/s800x360_jfs/t1/116056/7/15914/101482/5f4a7a0aEe8b7a7c0/7d0a4c1c1c1c1c1c.jpg' }
],
swiperOptions: {
pagination: {
el: '.swiper-pagination',
clickable: true
},
autoplay: {
delay: 3000,
disableOnInteraction: false
},
loop: true
}
}
}
}
</script>
<style scoped>
.swiper-container {
width: 100%;
height: 360px;
}
.swiper-slide img {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
自定义实现轮播图
如果不使用第三方插件,可以通过 Vue 的 transition 和定时器实现轮播效果。

<template>
<div class="carousel" @mouseenter="stopAutoPlay" @mouseleave="startAutoPlay">
<div class="carousel-list" :style="{ transform: `translateX(${-currentIndex * 100}%)` }">
<div class="carousel-item" v-for="(item, index) in banners" :key="index">
<img :src="item.image" alt="轮播图" />
</div>
</div>
<div class="carousel-dots">
<span
v-for="(item, index) in banners"
:key="index"
:class="{ active: currentIndex === index }"
@click="currentIndex = index"
></span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
banners: [
{ image: 'https://img10.360buyimg.com/babel/s800x360_jfs/t1/123258/21/5943/136401/5efbf328E8d5b78ef/3d2c7f9e7b7d9b3c.jpg' },
{ image: 'https://img10.360buyimg.com/babel/s800x360_jfs/t1/116056/7/15914/101482/5f4a7a0aEe8b7a7c0/7d0a4c1c1c1c1c1c.jpg' }
],
currentIndex: 0,
timer: null
}
},
mounted() {
this.startAutoPlay()
},
methods: {
startAutoPlay() {
this.timer = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.banners.length
}, 3000)
},
stopAutoPlay() {
clearInterval(this.timer)
}
}
}
</script>
<style scoped>
.carousel {
position: relative;
width: 100%;
height: 360px;
overflow: hidden;
}
.carousel-list {
display: flex;
transition: transform 0.5s ease;
}
.carousel-item {
flex-shrink: 0;
width: 100%;
height: 360px;
}
.carousel-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.carousel-dots {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.carousel-dots span {
width: 10px;
height: 10px;
margin: 0 5px;
border-radius: 50%;
background: #ccc;
cursor: pointer;
}
.carousel-dots span.active {
background: #f00;
}
</style>
关键点说明
轮播图实现的核心在于自动切换和手动控制。通过定时器实现自动播放,通过鼠标事件暂停和恢复播放。
使用第三方插件可以快速实现复杂功能,如无缝循环、手势滑动等。自定义实现更灵活,适合简单需求。
两种方式都可以实现京东风格的轮播图,选择取决于项目需求和技术偏好。






