vue如何设置定时器和清理定时器

Tina ·
更新时间:2024-09-20
· 532 次阅读

目录

设置定时器和清理定时器

1.在data中声明要设置的定时器名称

2.在mounted中创建定时器

定时器的使用全解

1.vue使用定时器

2代码实现

设置定时器和清理定时器

使用钩子函数对定时器进行清理,失败了

1.在data中声明要设置的定时器名称 data() {                 return {                                       timer: null  // 定时器名称               }         }, 2.在mounted中创建定时器 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);                                     }) 

哇,成功了...

定时器的使用全解 1.vue使用定时器

在vue中使用定时器,很多情况下,进入和退出vue界面,都没有清除定时器,从而导致有很多定时器一起工作,这样肯定是不行的,接下来就使用当用户进入界面时启用定时器,当用户离开当前界面时就清除定时器。

2代码实现 <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 定时器

需要 登录 后方可回复, 如果你还没有账号请 注册新账号