vue中使用$.once(‘hook:beforeDestory’,() => {})清理定時器

今天看代碼看到了一個自己沒有用過的

export default {
  data() {
    return {
      //下拉浮動標誌的顯示控制
      showFlag: true
    };
  },
  methods: {
    //點擊事件 實現點擊浮動下拉圖標,平滑滑動到主頁開頭部分(也是側邊欄的頭)
    moveToHome() {
      //目標元素距離頁面頂部的距離,在這裏是恆定值
      let total = document.getElementById("blog_main").offsetTop;
      move(total);
    }
  },
  created() {
    //定時器
    const timer = setInterval(() => {
      this.showFlag = !this.showFlag;
    }, 1000);
    this.$once("hook:beforeDestroy", () => {
      clearInterval(timer);
    });
  },
  mounted() {},
  components: {
    Typer
  }
};

在vue項目清理定時器,通常有兩種方法
方法一:
1、首先在vue實例的data中定義定時器的名稱,
2、在方法(methods)或者頁面初始化(mounted())的時候使用定時器
3、然後在頁面銷燬的生命週期函數(beforeDestroy())中銷燬定時器
實現代碼:

export default{
  data(){
    timer:null  
  },
  mounted(){
	  this.timer = setInterval(()=>{
	  //具體執行內容
	  console.log('1');
	},1000);
  }
  beforeDestory(){
    clearInterval(this.timer);
    this.timer = null;
  }
}

注: 第一種方法存在的問題是:
1、vue實例中需要有這個定時器的實例,感覺有點多餘;
2、 創建的定時器代碼和銷燬定時器的代碼沒有放在一起,通常很容易忘記去清理這個定時器,不容易維護;

因此,更推薦第二種方法,使用this.$once(‘hook:beforeDestory’,()=>{});

方法二:直接在需要定時器的方法或者生命週期函數中聲明並銷燬
實現代碼:

export default{
  methods:{
    fun1(){
      const timer = setInterval(()=>{
      	//具體執行代碼
        console.log('1');
      },1000);
      this.$once('hook:beforeDestory',()=>{
        clearInterval(timer);
        timer = null;
      })
    }
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章