在項目中,我們經常會使用到定時器setInterval(),可是很多時候我們會發現,即使我退出當前頁面,定時器依然在工作,非常消耗內存,所以我們要進行手動清理:
將定時器保存在變量中,退出頁面時清除變量
1.定義空的變量
data: function (){
return {
timer: null
}
}
2.定義定時器
methods: {
setTimer: function () {
this.timer = setInterval( () => {
.....
}, 1000)
}
}
3.進入和退出時清除定時器
mounted() {
clearInterval(this.timer)
},
distroyed: function () {
clearInterval(this.timer)
}