vue 實(shí)現(xiàn)setInterval 創(chuàng)建和銷毀實(shí)例
問題
setInterval 是間隔調(diào)用,與之類似的還有 setTimeout。這兩個(gè) API 通常用來做 ajax 短連接輪詢數(shù)據(jù)。
比如有一個(gè) logs.vue 是用來展示某個(gè)正在執(zhí)行的進(jìn)程產(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>
這段代碼看上去沒啥問題,但是測(cè)試的時(shí)候你會(huì)發(fā)現(xiàn),有時(shí)候路由已經(jīng)跳轉(zhuǎn)了,獲取進(jìn)程日志的接口依然在不斷調(diào)用,甚至,有時(shí)候接口調(diào)用速度非常快,一秒可能有好幾個(gè)請(qǐng)求。
分析
beforeDestory 是組件銷毀前的生命周期的鉤子,這個(gè)鉤子函數(shù)一定會(huì)調(diào)用,但是能不能徹底銷毀 setTimeout 呢?答案是不能。
打開控制臺(tái)就能看到不斷打印出來的 id
這是因?yàn)椋看问褂?clearTimeout 清除掉的是上一次的 id, 而不是本次正要執(zhí)行的,這種情況,對(duì)于使用 setInterval 也是一樣的。
根本原因在于,每次調(diào)用 getData, this.timer 是在不斷的被賦予新的值,而不是一成不變的。
在以前的原生 js 中,我們通常這樣寫:
var timer = nullfunction init(){ timer = setInterval(function(){ getData() })}function getData(){}window.onload = initwindow.onunload = function(){ clearInterval(timer)}
由于上面的 timer 始終保持一個(gè)值,所以這里的清除是有效的
解決
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>
這樣寫,還解決了兩個(gè)潛在問題
在組件實(shí)例中保存這個(gè) timer,最好只有生命周期鉤子有訪問它的權(quán)限。但是實(shí)例中的 timer 會(huì)視為雜物
如果建立代碼獨(dú)立于清理代碼,會(huì)使得我們比較難于程序化地清理所建立的東西
如果你是在項(xiàng)目中引入了 ts,那么可能會(huì)導(dǎo)致在組件銷毀的時(shí)候,定時(shí)器不能成功清除,這時(shí)候,你需要使用
const timer = window.setTimeout(()=>{ this.getData()}, 1000)this.$once(’hook:beforeDestroy’, function () { window.clearTimeout(timer)})
如果你漏掉了其中一個(gè) window,那么很可能會(huì)遇上類似的 ts 報(bào)錯(cuò):Type ’Timer’ is not assignable to type ’number’,這是因?yàn)?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 ,通常還有一些第三方庫的對(duì)象示例,如 timePicker,datePicker,echarts圖表等。
mounted: function () { // Pikaday 是一個(gè)第三方日期選擇器的庫 var picker = new Pikaday({ field: this.$refs.input, format: ’YYYY-MM-DD’ }) // 在組件被銷毀之前,也銷毀這個(gè)日期選擇器。 this.$once(’hook:beforeDestroy’, function () { picker.destroy() })}
以上這篇vue 實(shí)現(xiàn)setInterval 創(chuàng)建和銷毀實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
