1.data中定義
timer: null
2.methods中寫方法
this.timer = setInterval(function () { // 你的邏輯判斷 }, 2000)
3.beforeDestroy ---實例銷毀之前調用 清除定時器
beforeDestroy() { clearInterval(this.timer) this.timer = null }
4.解決這個問題的關鍵
updated() { this.getBotChart() // 由於數據時刻變化,所以要在updated中調用 window.clearInterval(this.timer) // 關鍵 },
5.注意點
當前路由使用 <keep-alive> 緩存,離開當前路由不會直接調用 beforeDestroy 和 beforeDestroy 銷毀,需要使用路由鈎子函數主動的調用 beforeRouteLeave(to, from, next) { this.$destroy(); next(); }