1. 程式人生 > 程式設計 >淺談vue 元件中的setInterval方法和window的不同

淺談vue 元件中的setInterval方法和window的不同

vue元件中,this指向例項,【例項中重寫了setInterval等一整套方法】。所以,千萬不能和 window 下掛載的方法混用

具體不同在於,window.setInterval執行完比後返回一個id,而vue例項中返回【定時器物件】,當然該物件中包含一個_id的私有屬性

因為 clearInterval 方法引數是id,所以最佳實踐是統一使用 window 的方法,不要使用 vue元件的方法

vue中的定時器方法,要使用箭頭函式,不要出現 const that = this 的寫法

//正確的用法
mounted() {
 // 如果不加 window ,則會使用 vue例項的方法,將無法清除定時器
 this.timer = window.setInterval(() => {
  this.date = new Date();
 },2000);
 console.log(this.timer);//number
},methods: {
 clearTimer() {
  window.clearInterval(this.timer);
  this.timer = null;
 }
}

補充知識:vue 切換頁面 setInterval

vue 是單頁面應用,路由切換後,定時器並不會自動關閉,需要手動清除,當頁面被銷燬時,清除定時器即可。

mounted(){
   clearInterval(this.timer);
   this.setTimer();
  },destroyed(){
  clearInterval(this.timer)
 }

以上這篇淺談vue 元件中的setInterval方法和window的不同就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。