vue中定时器设置和关闭页面时关闭定时器
我看了别人写的博客关于设置和清除定时器都比较复杂,我感觉其实很简单的几行代码就好。把我的写法记录一下。methods中setTime() //设置定时器{this.clearTimeSet=setInterval(() => {this.webSocketClientOnopen();}, 1000);},clearTime() //清除定时器{cl...
·
我看了别人写的博客关于设置和清除定时器都比较复杂,我感觉其实很简单的几行代码就好。把我的写法记录一下。
methods中
setTime() { //设置定时器
this.clearTimeSet=setInterval(() => {
this.webSocketClientOnopen();
}, 1000);
},
clearTime() { //清除定时器
clearInterval(this.clearTimeSet);
}
mounted 中
mounted : { //页面加载完毕就开始加载定时器
this.setTime();
}
beforeDestroy() { //页面关闭时清除定时器
clearInterval(this.clearTimeSet);
},
还有在tab页面加定时器和销毁定时器
stro() { //主页A
this.timeClss = setInterval(() => {
this.getFirstList()
}, 5 * 100)
},
twosli() {// 主页B
this.times = setInterval(() => {
this.getThirdList()
}, 5 * 100)
},
clearTime() { // 主页A 清除
clearInterval(this.timeClss)
},
clearcloss() { // 主页B 清除
clearInterval(this.times)
},
handleClick(tab, event) { // 每个tab点击切换的函数方法
if(tab.label == '主页A'){
this.getFirstList()
this.stro()
this.clearcloss()
}else if(tab.label == '工单A'){
this.getSecList()
this.clearTime()
this.clearcloss()
}else if(tab.label == '主页B'){
this.getThirdList()
this.twosli()
this.clearTime()
}else if(tab.label == '工单B'){
this.getFourList()
this.clearcloss()
this.clearTime()
}
}
首先,把定时器和清除定时器的方法分别写成函数方法,然后在handleClick
方法中当要切换tab的时候,在不需要的tab选项卡里调用定时器和清除定时器的方法就好了,这个就可以清除或设置定时器了!
更多推荐
已为社区贡献15条内容
所有评论(0)