vue 實現setInterval 創建和銷毀實例
問題
setInterval 是間隔調用,與之類似的還有 setTimeout。這兩個 API 通常用來做 ajax 短連接輪詢數據。
比如有一個 logs.vue 是用來展示某個正在執行的進程產生的日志:
<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>
這段代碼看上去沒啥問題,但是測試的時候你會發現,有時候路由已經跳轉了,獲取進程日志的接口依然在不斷調用,甚至,有時候接口調用速度非常快,一秒可能有好幾個請求。
分析
beforeDestory 是組件銷毀前的生命周期的鉤子,這個鉤子函數一定會調用,但是能不能徹底銷毀 setTimeout 呢?答案是不能。
打開控制臺就能看到不斷打印出來的 id
這是因為,每次使用 clearTimeout 清除掉的是上一次的 id, 而不是本次正要執行的,這種情況,對于使用 setInterval 也是一樣的。
根本原因在于,每次調用 getData, this.timer 是在不斷的被賦予新的值,而不是一成不變的。
在以前的原生 js 中,我們通常這樣寫:
var timer = nullfunction init(){ timer = setInterval(function(){ getData() })}function getData(){}window.onload = initwindow.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,最好只有生命周期鉤子有訪問它的權限。但是實例中的 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,
結論
我們可以通過 程序化的事件偵聽器 來監聽銷毀我們創建的任何代碼示例
除了 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 實現setInterval 創建和銷毀實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: