vue 定时器 不断切换组件 定时器越来越快的问题

1.data中定义

 timer: null

2.methods中写方法

this.timer = setInterval(function () {
      // 你的逻辑判断
     }, 2000)

3.beforeDestroy ---实例销毁之前调用 清除定时器

beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  }

4.解决这个问题的关键

updated() {
    this.getBotChart() // 由于数据时刻变化,所以要在updated中调用
    window.clearInterval(this.timer) // 关键
  },

5.注意点

当前路由使用 <keep-alive> 缓存,离开当前路由不会直接调用 beforeDestroy 和 beforeDestroy 销毁,需要使用路由钩子函数主动的调用

beforeRouteLeave(to, from, next) {
  this.$destroy();
  next();
}
原文地址:https://www.cnblogs.com/WorldEye/p/13998397.html