vue 定时器的问题

在项目中,我们经常会使用到定时器setInterval(),可是很多时候我们会发现,即使我退出当前页面,定时器依然在工作,非常消耗内存,所以我们要进行手动清理:

将定时器保存在变量中,退出页面时清除变量

1.定义空的变量

data: function (){

  return {

    timer: null

  }

}

2.定义定时器

methods: {

  setTimer: function () {

    this.timer = setInterval( () => {

        .....  

      }, 1000)

  }

}

3.进入和退出时清除定时器

mounted() {

  clearInterval(this.timer)

},

distroyed: function () {

  clearInterval(this.timer)

}

原文地址:https://www.cnblogs.com/wangqiao170/p/9037021.html