淺談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的不同就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: