vue 如何清除定时器

在页面中需要定时刷新局部数据,在数据变化是否频繁的情况下,没有必要使用webSocket,因为数据变化频繁,数据实时变化太快看不清楚。因此页面会定时调用后台接口以达到实时刷新数据的效果。

  1、在data中定义一个定时器变量,timer

  2、在mounted中把定时器的复制为timer

  3、页面离开时,在destroyed中清除定时器已经timer

data() {
  return {
    timer:null, //定时器名称
  }
},
created() {
  this.getHangTotal();
},
mounted() {
  this.timer = setInterval(
    this.getHangTotal, 10000
  );
},
destroyed(){
  clearInterval(this.timer);  // 清除定时器
  this.timer = null;
},
methods: {
  getHangTotal(){ 
      //………… 
    }
}
原文地址:https://www.cnblogs.com/luoxuemei/p/10301966.html