vue定时器设置和关闭页面时关闭定时器方式
作者:肖邦的交响乐
这篇文章主要介绍了vue定时器设置和关闭页面时关闭定时器方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
vue定时器设置和关闭页面时关闭定时器
我看了别人写的博客关于设置和清除定时器都比较复杂,我感觉其实很简单的几行代码就好。
把我的写法记录一下。
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选项卡里调用定时器和清除定时器的方法就好了,这个就可以清除或设置定时器了!
vue定时器的使用全解
vue使用定时器
在vue中使用定时器,很多情况下,进入和退出vue界面,都没有清除定时器,从而导致有很多定时器一起工作,这样肯定是不行的,接下来就使用当用户进入界面时启用定时器,当用户离开当前界面时就清除定时器。
代码实现
<template>
</template>
<script>
import store from '@/store'
import Vue from 'vue'
export default {
name: "test",
data () {
return {
timer: null
}
},
methods: {
setTimer() {
if(this.timer == null) {
this.timer = setInterval( () => {
console.log('开始定时...每过一秒执行一次')
}, 1000)
}
}
},
created: function() {
this.getFamilyBase_info()
// 每次进入界面时,先清除之前的所有定时器,然后启动新的定时器
clearInterval(this.timer)
this.timer = null
this.setTimer()
},
destroyed: function () {
// 每次离开当前界面时,清除定时器
clearInterval(this.timer)
this.timer = null
}
}
</script>
<style scoped>
</style>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
