vue項目中使用$.once(‘hook:beforeDestory‘,() => {})用法
一、清理定時器問題
在vue項目通常我們清理定時器的方法時,通常有兩種方法
方法一:
1、首先在vue實例的data中定義定時器的名稱:
export default{ data(){ timer:null } }
2、在方法(methods)或者頁面初始化(mounted())的時候使用定時器
this.timer = setInterval(()=>{ //需要做的事情 },1000);
3、然后在頁面銷毀的生命周期函數(beforeDestroy())中銷毀定時器
export default{ data(){ timer:null }, beforeDestroy(){ clearInterval(this.timer); this.timer = null; } }
注: 第一種方法確實是可行的,可是存在的問題是:
1、vue實例中需要有這個定時器的實例,感覺有點多余;
2、 創建的定時器代碼和銷毀定時器的代碼沒有放在一起,通常很容易忘記去清理這個定時器,不容易維護;
因此,更推薦第二種方法,使用this.$once(‘hook:beforeDestroy’,()=>{});
方法二:直接在需要定時器的方法或者生命周期函數中聲明並銷毀,代碼如下:
export default{ methods:{ fun1(){ let timer = setInterval(()=>{ //需要做的事情 console.log(11111); },1000); this.$once('hook:beforeDestroy',()=>{ clearInterval(timer); timer = null; }) } } }
二、取消監聽事件,取消事件總線的監聽比如
const getname = ()=>{xxxx;console.log(1)}
this.$bus.$on(GET_NAME,getname ); vue項目中使用$.once(‘hook:beforeDestory‘,() => {})可以在事件使用完離開頁面時銷毀 this.$once('hook:beforeDestroy', () => { this.$bus.$off(GET_NAME, getname) })