在项目中,初次接触vue,看了轮播插件vue-swiper等,好多都是左右切换的。个人强迫症比较严重,就要单页切换样式,就手写了一个。
功能:自动轮播,上一页下一页,点击小圆点切换大图。基本轮播要求的都实现了。。
缺点:毕竟不是专业的测试,自测是没有问题的。 当然,欢迎大家测出问题告知一声。
目前踩了两个坑:
- 数组里的图片只能放在static中;
- setInterval中的this不是只想vue,而是window!)
上代码:随意来一个组件,直接粘贴复制即可(图片自己准备)
html片段
<template>
<div id="firstPage">
<!-- 轮播 -->
<div class="sliderBox" @mouseenter="stopPlay()" @mouseleave="autoPlay()">
<img id="img" :src="url" style="100%;">
<div class="leftImg" @click="preImg()"><img src="../assets/left.png" style="100%;"></div>
<div class="rightImg" @click="nextImg()"><img src="../assets/right.png" style="100%;"></div>
<ul id="sliderUl" class="sliderUl">
<li @click='clickImgLi(0)' :class="{'activeImg':setIndex==3||setIndex==0}" ></li>
<li @click='clickImgLi(1)' :class="{'activeImg':setIndex==1}" ></li>
<li @click='clickImgLi(2)' :class="{'activeImg':setIndex==2}" ></li>
</ul>
</div>
<div>测试数据:{{setIndex}}</div>
</div>
</template>
js
<script>
export default {
data () {
return {
setIndex:1,
imgs: ["/static/image/lbt1.jpg","/static/image/lbt2.jpg","/static/image/lbt3.jpg"],
url:"/static/image/lbt1.jpg",
timer:""
}
},
mounted:function(){
this.autoPlay()
},
methods: {
autoPlay(){
var _this =this
_this.timer=setInterval(function(){
if(_this.setIndex ==3){
_this.setIndex=0;
}
_this.url=_this.imgs[_this.setIndex];
_this.setIndex+=1;
},4000)
},
stopPlay(){
var _this =this
clearInterval(_this.timer)
},
nextImg(){
if(this.setIndex ==3){
this.setIndex=0;
}
this.setIndex+=1;
this.url=this.imgs[this.setIndex];
},
preImg(){
if(this.setIndex ==0){
this.setIndex=3;
}
this.url=this.imgs[this.setIndex];
this.setIndex-=1;
},
clickImgLi(thisIndex){
this.setIndex=thisIndex;
this.url=this.imgs[this.setIndex];
}
}
}
</script>
css
<style scoped>
.sliderBox{100%;height:354px;overflow: hidden;position: relative}
.leftImg,.rightImg{60px;height:60px;position:absolute;top:120px;}
.leftImg{left:100px;}
.rightImg{right:100px;}
.sliderUl{position: absolute;left: 45%;bottom: 30px; 72px;}
.sliderUl li{ 14px; height: 14px; float: left; margin-right: 10px; background-color: red
/*background-image: url("../assets/lx.png" );opacity: 0.5 */
}
#sliderUl .activeImg{background-color: black }
</style>