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();
  },
};

结果发现,定时器成功清除

原文地址:https://www.cnblogs.com/whatarey/p/14490632.html