Vue.component('slider',{ template:'#slider', props:['pics'], data:function(){ return { currentIndex:0, timer:null } }, created:function(){ this.setTime(); }, computed:{ left:function(){ return this.currentIndex * 600 } }, methods:{ clearTime:function(){ if(this.timer){ clearInterval(this.timer); } }, setTime:function(){ if(this.timer){ clearInterval(this.timer); } var that = this; this.timer = setInterval(function(){ if(that.currentIndex<that.pics.length-1) that.currentIndex++; else that.currentIndex = 0; },2000); }, tab:function(index){ this.currentIndex = index; this.setTime(); } } }) new Vue({ el:'#app', data:{ imgs:[ {desc:1}, {desc:2}, {desc:3}, {desc:4}, {desc:5} ] } })
<div id="app"> <slider :pics='imgs'></slider> </div> <script type="text/x-template" id="slider"> <div class="slider" @mouseover="clearTime()" @mouseout="setTime()"> <div class="imgs" :style="{left:-left+'px', width:600*pics.length+'px'}"> <div class="item" v-for="item in pics"> <span>{{item.desc}}</span> </div> </div> <div class="dots"> <span class="dot" v-for="(item, index) in pics" @click="tab(index)" :class="{active:index==currentIndex}"></span> </div> </div> </script>
.slider{ position:relative; width:600px; overflow:hidden; } .imgs{ position:relative; top:0; left:0; transition: left .5s ease; } .imgs .item{ width:600px; height:200px; float:left; background-color:blue; text-align:center; } .item span{ font-size:50px; color:yellow; } .dots{ position:absolute; margin-left:50%; transform:translate(-50%,0); bottom:10px; } .dot{ width:4px; height:4px; display:inline-block; background-color:white; margin:2px; } .dot.active{ background-color:red; }