vue定時器設置和關(guān)閉頁面時關(guān)閉定時器方式
vue定時器設置和關(guān)閉頁面時關(guān)閉定時器
我看了別人寫的博客關(guān)于設置和清除定時器都比較復雜,我感覺其實很簡單的幾行代碼就好。
把我的寫法記錄一下。
methods中
setTime() { //設置定時器 ? this.clearTimeSet=setInterval(() => { ? ? this.webSocketClientOnopen(); ? }, 1000); }, clearTime() { //清除定時器 ? clearInterval(this.clearTimeSet); }
mounted 中
mounted : { //頁面加載完畢就開始加載定時器 ? this.setTime(); }
beforeDestroy() { ? ?//頁面關(guān)閉時清除定時器 ? ? clearInterval(this.clearTimeSet); },
還有在tab頁面加定時器和銷毀定時器
stro() { //主頁A ? ? ? ? ? ? this.timeClss = setInterval(() => { ? ? ? ? ? ? ? ? this.getFirstList() ? ? ? ? ? ? }, 5 * 100) ? ? ? ? }, ? ? ? ? twosli() {// 主頁B ? ? ? ? ? ? this.times = ?setInterval(() => { ? ? ? ? ? ? ? ? this.getThirdList() ? ? ? ? ? ? }, 5 * 100) ? ? ? ? }, ? ? ? ? clearTime() { // 主頁A 清除 ? ? ? ? ? ? clearInterval(this.timeClss) ? ? ? ? }, ? ? ? ? clearcloss() { // 主頁B 清除 ? ? ? ? ? ? clearInterval(this.times) ? ? ? ? },
?handleClick(tab, event) { // 每個tab點擊切換的函數(shù)方法 ? ? ? ? ? ? if(tab.label == '主頁A'){ ? ? ? ? ? ? ? ? this.getFirstList() ? ? ? ? ? ? ? ? this.stro()? ? ? ? ? ? ? ? ? this.clearcloss() ? ? ? ? ? ? }else if(tab.label == '工單A'){ ? ? ? ? ? ? ? ? this.getSecList() ? ? ? ? ? ? ? ? this.clearTime() ? ? ? ? ? ? ? ? this.clearcloss() ? ? ? ? ? ? }else if(tab.label == '主頁B'){ ? ? ? ? ? ? ? ? this.getThirdList() ? ? ? ? ? ? ? ? this.twosli() ? ? ? ? ? ? ? ? this.clearTime() ? ? ? ? ? ? }else if(tab.label == '工單B'){ ? ? ? ? ? ? ? ? this.getFourList() ? ? ? ? ? ? ? ? this.clearcloss() ? ? ? ? ? ? ? ? this.clearTime() ? ? ? ? ? ? } ? ? ? ? }
首先,把定時器和清除定時器的方法分別寫成函數(shù)方法,然后在handleClick方法中當要切換tab的時候,在不需要的tab選項卡里調(diào)用定時器和清除定時器的方法就好了,這個就可以清除或設置定時器了!
vue定時器的使用全解
vue使用定時器
在vue中使用定時器,很多情況下,進入和退出vue界面,都沒有清除定時器,從而導致有很多定時器一起工作,這樣肯定是不行的,接下來就使用當用戶進入界面時啟用定時器,當用戶離開當前界面時就清除定時器。
代碼實現(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>
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue自定v-model實現(xiàn)表單數(shù)據(jù)雙向綁定問題
vue.js的一大功能便是實現(xiàn)數(shù)據(jù)的雙向綁定。這篇文章主要介紹了vue自定v-model實現(xiàn) 表單數(shù)據(jù)雙向綁定的相關(guān)知識,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-09-09Vue向后臺傳數(shù)組數(shù)據(jù),springboot接收vue傳的數(shù)組數(shù)據(jù)實例
這篇文章主要介紹了Vue向后臺傳數(shù)組數(shù)據(jù),springboot接收vue傳的數(shù)組數(shù)據(jù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11vue3 Teleport瞬間移動函數(shù)使用方法詳解
這篇文章主要為大家詳細介紹了vue3 Teleport瞬間移動函數(shù)使用方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-03-03