vue跳转页面,beforeDestroy和destroyed不执行

2,676 阅读1分钟

在项目中遇到页面中使用定时器,但是跳转至其他页面定时器未清楚的情况,代码如下:

 data() {
    return {
    	myInterval:null,
    }
 },
 mounted() {
    that.myInterval = setInterval(() => {
      that.tempCheck();
      that.eletrcCheck();
      that.warnCheck();
    }, 3000);
    
  },
    destroyed() {
     clearInterval(this.myInterval);
    this.myInterval = null
  },

查找资料后发现是因为使用了keep-alive 解决方法如下

  beforeRouteLeave(to, from, next) {
    clearInterval(this.myInterval);
    this.myInterval = null
    next();
  }