欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue如何設(shè)置定時(shí)器和清理定時(shí)器

 更新時(shí)間:2022年05月30日 09:28:48   作者:梅鴻樓  
這篇文章主要介紹了vue如何設(shè)置定時(shí)器和清理定時(shí)器,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

設(shè)置定時(shí)器和清理定時(shí)器

使用鉤子函數(shù)對定時(shí)器進(jìn)行清理,失敗了

1.在data中聲明要設(shè)置的定時(shí)器名稱

data() { ? ? ? ? ? ?
? ? return { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? timer: null ?// 定時(shí)器名稱 ? ? ? ? ?
? ? } ? ? ? ?
},

2.在mounted中創(chuàng)建定時(shí)器

this.timer = (() => {
? ? // 某些操作
}, 5000)復(fù)制代碼3、在頁面注銷時(shí)清理定時(shí)器:beforeDestroy() {
? ? clearInterval(this.timer); ? ? ? ?
? ? this.timer = null;
}

然鵝,并沒什么卵用,在切換頁面后,定時(shí)任務(wù)依然頑強(qiáng)的奔跑著。

beforeDestroy() {
? ? clearInterval(this.timer); ? ? ? ?
? ? this.timer = null;
? ? console.log(this.timer) ? ? ? ? ? ?//輸出為: null,但是任務(wù)依然在繼續(xù)運(yùn)行
}

可能是我的姿勢不對吧。害羞.jpg經(jīng)過在各大論壇一番查找發(fā)現(xiàn):通過$once這個(gè)事件偵聽器在定義完定時(shí)器之后的位置來清除定時(shí)器:

const timer = setInterval(() =>{ ? ? ? ? ? ? ? ? ? ?
? ? // 某些定時(shí)器操作 ? ? ? ? ? ? ? ?
}, 5000); ? ? ? ? ? ?
// 通過$once來監(jiān)聽定時(shí)器
// 在beforeDestroy鉤子觸發(fā)時(shí)清除定時(shí)器
this.$once('hook:beforeDestroy', () => { ? ? ? ? ? ?
? ? clearInterval(timer); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
})?

哇,成功了...

定時(shí)器的使用全解

1.vue使用定時(shí)器

在vue中使用定時(shí)器,很多情況下,進(jìn)入和退出vue界面,都沒有清除定時(shí)器,從而導(dǎo)致有很多定時(shí)器一起工作,這樣肯定是不行的,接下來就使用當(dāng)用戶進(jìn)入界面時(shí)啟用定時(shí)器,當(dāng)用戶離開當(dāng)前界面時(shí)就清除定時(shí)器。

2代碼實(shí)現(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('開始定時(shí)...每過一秒執(zhí)行一次')
                    }, 1000)
                }
            }
        },
        created: function() {
            this.getFamilyBase_info()
            // 每次進(jìn)入界面時(shí),先清除之前的所有定時(shí)器,然后啟動(dòng)新的定時(shí)器
            clearInterval(this.timer)
            this.timer = null
            this.setTimer()
        },
        destroyed: function () {
            // 每次離開當(dāng)前界面時(shí),清除定時(shí)器
            clearInterval(this.timer)
            this.timer = null
        }
    }
</script>
<style scoped>
</style>

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論