css
<style>
#app {
position: relative;
width: 500px;
margin: 0 auto;
text-align: center;
}
.dot {
width: 200px;
display: flex;
justify-content: space-around;
margin: 0 auto;
margin-top: -30px;
}
.dot span {
background-color: #fff;
width: 12px;
height: 12px;
border-radius: 50%;
cursor: pointer;
}
.dot .on {
background-color: #0f0;
}
button {
width: 30px;
height: 30px;
background-color: rgba(255, 255, 255, .5);
border: none;
}
#app .lt {
position: absolute;
left: 50px;
margin-left: -50px;
top: 50%;
font-weight: bold;
font-size: 16px;
}
#app .gt {
position: absolute;
left: 50px;
margin-left: 420px;
top: 50%;
font-weight: bold;
font-size: 16px;
}
</style>
HTML
<div id="app">
<h1>轮播图</h1>
<swiper :gallery="gallery" style="width:500px"></swiper>
</div>
vue.js
<script src="js/vue.min.js"></script>
<script src="js/swiper.js"></script>
<script>
new Vue({
el: "#app",
components: { swiper },
data() {
return {
// 存放轮播图的图片
gallery: [
" img/1.jpg",
" img/2.jpg",
" img/3.jpg",
" img/4.jpg"
],
}
}
})
</script>
组件 swiper
var swiper = {
template: `<div class="swiper" @mouseenter="stop" @mouseleave="play">
<img
v-show="current===index"
v-for="(item,index) in gallery" :key="item" :src="item" width="100%"/>
<div class="dot">
<span @click="current=item-1" :class="{'on':current===item-1}"
v-for="item in gallery.length">
</span>
</div>
<button class="lt" @click="lt"><</button>
<button class="gt" @click="gt">></button>
</div>`,
// 循环gallery的长度得到指示器 1 2 3 4
// 单击1,2,3 4改变 current 实现幻灯片单击切换
props: {
// 接收父组件传递过的参数gallery
gallery: {
type: Array,
// 引用类型的默认值必须函数函数返回
// 如果没有默认为空
default() { return [] }
}
},
data() {
return {
// 当前需要显示的幻灯片第current张 默认显示幻灯片第0张
current: 0,
timer: null
}
},
methods: {
// 播放幻灯片
play() {
// 每隔3秒执行current加1(幻灯片随着current切换了)
timer = setInterval(() => {
this.current++;
// 如果超过幻灯片的长度等于0
if (this.current >= this.gallery.length) {
this.current = 0;
}
}, 3000)
},
stop() {
clearInterval(timer)
},
lt() {
if (this.current <= 0) {
this.current = this.gallery.length;
}
this.current--;
},
gt() {
this.current++;
if (this.current >= this.gallery.length) {
this.current = 0;
}
}
},
// 组件创建完毕 自动播放
created() {
this.play();
}
}