解决beforeDestroy中清除定时器失效的问题

在项目中,我们经常有在离开页面时需要清除定时器的需求,一般会在beforeDestroy中添加,代码展示如下:

beforeDestroy() {
    
    
   this.stopTimer()
},

这样有时候会没有效果,因为只是页面切换了。
这时候可以使用 beforeRouteLeave,展示如下:

beforeRouteLeave (to, from, next) {
    
    
  this.stopTimer()
  next()
},

这样大概率就可以解决此类问题,完整代码如下:

methods: {
    
    
  startTimer() {
    
    
    this.timer = setInterval(() => {
    
    
      setTimeout(() => {
    
     this.getKeywordsspider(), 						this.getProgressBarPlatform(), this.getOnlineUserNum() }, 0)
    }, 30000)
  },
  stopTimer() {
    
    
    clearInterval(this.timer)
  },
},
//离开页面清除定时器失效问题
beforeRouteLeave (to, from, next) {
    
    
  this.stopTimer()
  next()
},
beforeDestroy() {
    
    
  this.stopTimer()
},

请注意: beforeRouteLeave 中 调用方法后,必须添加 next()才可以。
以上内容参考的【解决vue后台管理系统 离开页面清除定时器失效问题】这篇博客,可点击查看。
记录收藏,以备急用。

猜你喜欢

转载自blog.csdn.net/weixin_62733705/article/details/133946783
今日推荐