vue如何設置定時器和清理定時器
更新時間:2022年05月30日 09:28:48 作者:梅鴻樓
這篇文章主要介紹了vue如何設置定時器和清理定時器,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
設置定時器和清理定時器
使用鉤子函數對定時器進行清理,失敗了
1.在data中聲明要設置的定時器名稱
data() { ? ? ? ? ? ? ? ? return { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? timer: null ?// 定時器名稱 ? ? ? ? ? ? ? } ? ? ? ? },
2.在mounted中創(chuàng)建定時器
this.timer = (() => { ? ? // 某些操作 }, 5000)復制代碼3、在頁面注銷時清理定時器:beforeDestroy() { ? ? clearInterval(this.timer); ? ? ? ? ? ? this.timer = null; }
然鵝,并沒什么卵用,在切換頁面后,定時任務依然頑強的奔跑著。
beforeDestroy() { ? ? clearInterval(this.timer); ? ? ? ? ? ? this.timer = null; ? ? console.log(this.timer) ? ? ? ? ? ?//輸出為: null,但是任務依然在繼續(xù)運行 }
可能是我的姿勢不對吧。害羞.jpg經過在各大論壇一番查找發(fā)現:通過$once這個事件偵聽器在定義完定時器之后的位置來清除定時器:
const timer = setInterval(() =>{ ? ? ? ? ? ? ? ? ? ? ? ? // 某些定時器操作 ? ? ? ? ? ? ? ? }, 5000); ? ? ? ? ? ? // 通過$once來監(jiān)聽定時器 // 在beforeDestroy鉤子觸發(fā)時清除定時器 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('開始定時...每過一秒執(zhí)行一次') }, 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 Element 分組+多選+可搜索Select選擇器實現示例
這篇文章主要介紹了Vue Element 分組+多選+可搜索Select選擇器實現示例,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07