vue里面使用定时器,刷新或重开网页后定时器效果不消失,显示效果混乱甚至导致浏览器崩溃;vue里定时器的this指向问题。
A,初始组件创建时代码;
data() {
return{
timer:null
}
}B,定时器代码
mounted(){
var that = this
this.timer = setInterval(function(){
that.flag = !that.flag
},1000)
}或
mounted(){
this.timer = setInterval(()=>{
this.flag = !this.flag
},1000)
}上面两种方式实现的定时器代码是等效的:function形式的定时器里的this指向的是window,用that保存this在才能正确的表示vue的实例;而箭头函数里的this指向的是外层不是箭头函数this,就是vue的实例,明显箭头函数的创建方式更简介优雅一些。
C,销毁组件时清除定时器:
beforeDestroy(){
clearInterval(this.timer)
this.timer = null;
}这样就能正确的在vue里使用定时器了。在vue中使用定时器出问题一般是没有正确的清除定时器和弄混了this的指向。