Vue清除子頁面定時器


我們的Index.vue 頁面 用了,a,b,c組件, a,b,c組件里面有 定時器來輪詢

 loadtime() {
      this.polling= setInterval(() => {
        setTimeout(() => {
          this.PostTipset();
        }, 0);
      }, 20000);
    },

當我們Index進行 頁面跳轉的時候,也許你會在 a,b,c組件事件方法寫上

  // activated(){ 
  //     this.loadtime(); // 開始輪詢
  // },
  // beforeRouteLeave(to, from, next) {
  //   // 路由跳轉前,清除輪詢
  //   next();
  //   if (this.polling) {
  //     clearInterval(this.polling);
  //     this.polling = null;
  //   }
  // },

但是,很可惜,這樣子,你的定時器還是在執行的, 而你在 beforeRouteLeave 方法里面打印的時候,會發現根本沒有進入這個方法,會誤以為自己寫錯了
於是你在 Index 定義這個 beforeRouteLeave 並且 打印,結果發現 ,Index 的 beforeRouteLeave 能夠打印

解決的方法是

 this.polling 修改為    window.mytime1
  loadtime() {
      window.mytime1 = setInterval(() => {
        setTimeout(() => {
          this.PostTipset();
        }, 0);
      }, 20000);
    },



在到Index 中增加 beforeRouteLeave 清除定時器

  beforeRouteLeave(to, from, next) {
    // 路由跳轉前,清除輪詢
    if (window.Mytimesummary) { 
      clearInterval(window.mytime1);
      clearInterval(window.mytime2);
      clearInterval(window.mytime3);
    }
    console.log("清除 time",to,from);
    next();
  },
};

結果發現,定時器成功清除


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM