关于vue销毁定时器的问题

797 阅读1分钟

image.png

在data内定义定时器的名字方便清除

data() {
    return {
      timer:null,//定时器
    };
  },

在create内调用

 created() {
    this.getTime();
    this.timer = setInterval(() => {
        this.getTime();//这个随便调用什么方法
      }, 1000);
  },
 
 在 beforeDestroy 周期销毁
 

```js
beforeDestroy(){
   console.log("销毁定时器");
   clearInterval(this.timer);
},

##小程序的定时器销毁方式

data:{
timer:null
}
  */
  onShow() {
    let _this = this;
		this.setData({
			timer: setInterval(() => {
				//_this.xx(); // 定时刷新
			}, 60000)
		})
  },
 /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.data.timer);
		this.setData({
			timer: null
		})
   },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.timer);
		this.setData({
			timer: null
		})
   },