设置定时器和清理定时器
使用钩子函数对定时器进行清理,失败了
1.在data中声明要设置的定时器名称
|
1
2
3
4
5
|
data() { return { timer: null // 定时器名称 } }, |
2.在mounted中创建定时器
|
1
2
3
4
5
6
|
this.timer = (() => { // 某些操作}, 5000)复制代码3、在页面注销时清理定时器:beforeDestroy() { clearInterval(this.timer); this.timer = null;} |
然鹅,并没什么卵用,在切换页面后,定时任务依然顽强的奔跑着。
|
1
2
3
4
5
|
beforeDestroy() { clearInterval(this.timer); this.timer = null; console.log(this.timer) //输出为: null,但是任务依然在继续运行} |
可能是我的姿势不对吧。害羞.jpg经过在各大论坛一番查找发现:通过$once这个事件侦听器在定义完定时器之后的位置来清除定时器:
|
1
2
3
4
5
6
7
8
|
const timer = setInterval(() =>{ // 某些定时器操作 }, 5000); // 通过$once来监听定时器// 在beforeDestroy钩子触发时清除定时器this.$once('hook:beforeDestroy', () => { clearInterval(timer); }) |
哇,成功了…
定时器的使用全解
1.vue使用定时器
在vue中使用定时器,很多情况下,进入和退出vue界面,都没有清除定时器,从而导致有很多定时器一起工作,这样肯定是不行的,接下来就使用当用户进入界面时启用定时器,当用户离开当前界面时就清除定时器。
2代码实现
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<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> |
转自:https://www.jb51.net/article/249786.htm