继续面向Vue新人:使用Vue写一个图片轮播组件(一)
六、自动播放与暂停前面的写的差不多了,到这里就非常简单了,写一个函数play:
play() {
if (this.timer) {
window.clearInterval(this.timer)
this.timer = null
}
this.timer = window.setInterval(() => {
this.move(600, -1, this.speed)
}, 4000)
}
除了初始化以后自动播放,还要通过mouseover和mouseleave来控制暂停与播放:
stop() {
window.clearInterval(this.timer)
this.timer = null
}
七、 两处小坑
1. window.onblur和window.onfocus
写到这里,基本功能都差不多了。但是如果把页面切换到别的页面,导致轮播图所在页面失焦,过一段时间再切回来会发现轮播狂转。原因是页面失焦以后,setInterval停止运行,但是如果切回来就会一次性把该走的一次性走完。解决的方法也很简单,当页面失焦时停止轮播,页面聚焦时开始轮播。
window.onblur = function() { this.stop() }.bind(this)
window.onfocus = function() { this.play() }.bind(this)
## 2. window.setInterval()小坑 ##
当定时器window.setInterval()在多个异步回调中使用时,就有可能在某种机率下开启多个执行队列,所以为了保险起见,不仅应该在该清除时清除定时器,还要在每次使用之前也清除一遍。
八、用props简单写两个对外接口props: {
initialSpeed: {
type: Number,
default: 30
},
initialInterval: {
type: Number,
default: 4
}
},
data() {
......
speed: this.initialSpeed
},
computed:{
interval() {
return this.initialInterval * 1000
}
}
然后再在相应的地方修改下就可以了。
完整的代码如下:
-
-
-
-
-
-
github地址
九、结语大概写完了这个组件,发现其实还有许多地方可以优化,this.distance和this.currentIndex耦合性很高,完全可以通过计算属性连到一起。还有过渡方式,用定时器的方法还是有些生硬,没有发挥出Vue的优势来。不过,第一个组件算是写完了,也费了一番力气。
作者:limingru
链接:https://juejin.im/post/5aaf0907f265da23870e9fed



