vue如何設(shè)置定時器和清理定時器
設(shè)置定時器和清理定時器
使用鉤子函數(shù)對定時器進行清理,失敗了
1.在data中聲明要設(shè)置的定時器名稱
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經(jīng)過在各大論壇一番查找發(fā)現(xiàn):通過$once這個事件偵聽器在定義完定時器之后的位置來清除定時器:
const timer = setInterval(() =>{ ? ? ? ? ? ? ? ? ? ?
? ? // 某些定時器操作 ? ? ? ? ? ? ? ?
}, 5000); ? ? ? ? ? ?
// 通過$once來監(jiān)聽定時器
// 在beforeDestroy鉤子觸發(fā)時清除定時器
this.$once('hook:beforeDestroy', () => { ? ? ? ? ? ?
? ? clearInterval(timer); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
})?哇,成功了...
定時器的使用全解
1.vue使用定時器
在vue中使用定時器,很多情況下,進入和退出vue界面,都沒有清除定時器,從而導致有很多定時器一起工作,這樣肯定是不行的,接下來就使用當用戶進入界面時啟用定時器,當用戶離開當前界面時就清除定時器。
2代碼實現(xiàn)
<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>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue Element 分組+多選+可搜索Select選擇器實現(xiàn)示例
這篇文章主要介紹了Vue Element 分組+多選+可搜索Select選擇器實現(xiàn)示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
vue.js實現(xiàn)開關(guān)(switch)組件實例代碼
這篇文章介紹了vue.js實現(xiàn)開關(guān)(switch)組件的實例代碼,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06

