vue2.0实现轮播
Vue 2.0 实现轮播的方法
使用第三方库 vue-awesome-swiper
安装 vue-awesome-swiper:
npm install vue-awesome-swiper@2.6.7 --save
在组件中引入并使用:
<template>
<swiper :options="swiperOption">
<swiper-slide v-for="(slide, index) in slides" :key="index">
<img :src="slide.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 {
slides: [
{ image: 'image1.jpg' },
{ image: 'image2.jpg' },
{ image: 'image3.jpg' }
],
swiperOption: {
pagination: {
el: '.swiper-pagination'
},
autoplay: {
delay: 3000
},
loop: true
}
}
}
}
</script>
原生实现轮播组件
创建一个基础轮播组件:
<template>
<div class="carousel">
<div class="slides" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
<div class="slide" v-for="(slide, index) in slides" :key="index">
<img :src="slide.image" alt="">
</div>
</div>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
slides: [
{ image: 'image1.jpg' },
{ image: 'image2.jpg' },
{ image: 'image3.jpg' }
]
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length
}
},
mounted() {
setInterval(this.next, 3000)
}
}
</script>
<style>
.carousel {
overflow: hidden;
position: relative;
width: 100%;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
}
</style>
使用过渡效果增强原生轮播
添加 Vue 过渡效果:
<template>
<div class="carousel">
<transition-group name="slide" tag="div" class="slides">
<div class="slide" v-for="(slide, index) in slides" :key="index" v-show="index === currentIndex">
<img :src="slide.image" alt="">
</div>
</transition-group>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<style>
.slide-enter-active, .slide-leave-active {
transition: opacity 0.5s, transform 0.5s;
}
.slide-enter {
opacity: 0;
transform: translateX(100%);
}
.slide-leave-to {
opacity: 0;
transform: translateX(-100%);
}
</style>
实现指示器功能
添加轮播指示点:
<template>
<div class="carousel">
<!-- 轮播内容 -->
<div class="indicators">
<span
v-for="(slide, index) in slides"
:key="index"
:class="{ active: index === currentIndex }"
@click="goTo(index)"
></span>
</div>
</div>
</template>
<script>
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>






