本篇内容介绍了“vue怎么设置定时器和清理定时器”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
使用钩子函数对定时器进行清理,失败了
data() {
return {
timer: null // 定时器名称
}
},
this.timer = (() => {
// 某些操作
}, 5000)3、在页面注销时清理定时器:beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}
然鹅,并没什么卵用,在切换页面后,定时任务依然顽强的奔跑着。
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
console.log(this.timer) //输出为: null,但是任务依然在继续运行
}
可能是我的姿势不对吧。害羞.jpg经过在各大论坛一番查找发现:通过$once这个事件侦听器在定义完定时器之后的位置来清除定时器:
const timer = setInterval(() =>{
// 某些定时器操作
}, 5000);
// 通过$once来监听定时器
// 在beforeDestroy钩子触发时清除定时器
this.$once('hook:beforeDestroy', () => {
clearInterval(timer);
})
哇,成功了...
在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>
“vue怎么设置定时器和清理定时器”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。