vue 實現(xiàn)setInterval 創(chuàng)建和銷毀實例
問題
setInterval 是間隔調(diào)用,與之類似的還有 setTimeout。這兩個 API 通常用來做 ajax 短連接輪詢數(shù)據(jù)。
比如有一個 logs.vue 是用來展示某個正在執(zhí)行的進程產(chǎn)生的日志:
<template> <div> <p v-for="item in logList" :key="item.time"> <span>{{"[" + item.time + "]"}}</span> <span>{{ item.log }}</span> </p> </div> </template> <script> import { Component, Vue, Watch, Prop, Emit } from 'vue-property-decorator' import { getLogList } from './api' @Component({}) export default class extends Vue { logList = [] timer = null mounted(){ this.getData() } async getData(){ let r = await getLogList() if(r && r.logList){ this.logList = r.logList } this.timer = setTimeout(()=>{ console.log(this.timer); this.getData() }, 1000) } beforeDestory(){ clearTimeout(this.timer) this.timer = null; } } </script>
這段代碼看上去沒啥問題,但是測試的時候你會發(fā)現(xiàn),有時候路由已經(jīng)跳轉(zhuǎn)了,獲取進程日志的接口依然在不斷調(diào)用,甚至,有時候接口調(diào)用速度非常快,一秒可能有好幾個請求。
分析
beforeDestory 是組件銷毀前的生命周期的鉤子,這個鉤子函數(shù)一定會調(diào)用,但是能不能徹底銷毀 setTimeout 呢?答案是不能。
打開控制臺就能看到不斷打印出來的 id
這是因為,每次使用 clearTimeout 清除掉的是上一次的 id, 而不是本次正要執(zhí)行的,這種情況,對于使用 setInterval 也是一樣的。
根本原因在于,每次調(diào)用 getData, this.timer 是在不斷的被賦予新的值,而不是一成不變的。
在以前的原生 js 中,我們通常這樣寫:
var timer = null function init(){ timer = setInterval(function(){ getData() }) } function getData(){} window.onload = init window.onunload = function(){ clearInterval(timer) }
由于上面的 timer 始終保持一個值,所以這里的清除是有效的
解決
vue 提供了 程序化的事件偵聽器 來處理這類邊界情況
按照文檔的說法,我們的代碼可以這樣來更改
<script> import { Component, Vue, Watch, Prop, Emit } from 'vue-property-decorator' import { getLogList } from './api' @Component({}) export default class extends Vue { logList = [] // timer = null mounted(){ this.getData() } async getData(){ let r = await getLogList() if(r && r.logList){ this.logList = r.logList } const timer = setTimeout(()=>{ this.getData() }, 1000) this.$once('hook:beforeDestroy', function () { clearTimeout(timer) }) } } </script>
這樣寫,還解決了兩個潛在問題
在組件實例中保存這個 timer,最好只有生命周期鉤子有訪問它的權(quán)限。但是實例中的 timer 會視為雜物
如果建立代碼獨立于清理代碼,會使得我們比較難于程序化地清理所建立的東西
如果你是在項目中引入了 ts,那么可能會導致在組件銷毀的時候,定時器不能成功清除,這時候,你需要使用
const timer = window.setTimeout(()=>{ this.getData() }, 1000) this.$once('hook:beforeDestroy', function () { window.clearTimeout(timer) })
如果你漏掉了其中一個 window,那么很可能會遇上類似的 ts 報錯:Type 'Timer' is not assignable to type 'number',這是因為 node typings
It seems like you are using node typings which override setInterval() as something that returns NodeJS.Timer. If you're running in the browser, it doesn't make a whole lot of sense to use these,
結(jié)論
我們可以通過 程序化的事件偵聽器 來監(jiān)聽銷毀我們創(chuàng)建的任何代碼示例
除了 setTimeout 和 setInterval ,通常還有一些第三方庫的對象示例,如 timePicker,datePicker,echarts圖表等。
mounted: function () { // Pikaday 是一個第三方日期選擇器的庫 var picker = new Pikaday({ field: this.$refs.input, format: 'YYYY-MM-DD' }) // 在組件被銷毀之前,也銷毀這個日期選擇器。 this.$once('hook:beforeDestroy', function () { picker.destroy() }) }
以上這篇vue 實現(xiàn)setInterval 創(chuàng)建和銷毀實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue3結(jié)合ts從零實現(xiàn)vueuse的useRouteQuery方法
這篇文章主要為大家詳細介紹了如何使用vue3與ts從零實現(xiàn)一個類vueuse的useRouteQuery方法,并解決vueuse的useRouteQuery方法存在的一些問題,感興趣的可以了解下2024-03-03Vue項目保持element組件同行,設置組件不自動換行問題
這篇文章主要介紹了Vue項目保持element組件同行,設置組件不自動換行問題。具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02Vue 集成 PDF.js 實現(xiàn) PDF 預覽和添加水印的步驟
這篇文章主要介紹了如何在 Vue 中集成 Mozilla/PDF.js ,實現(xiàn)自定義的 PDF 預覽器,以及給被預覽的 PDF 添加水印2021-01-01