其他分享
首页 > 其他分享> > Vue项目中使用和清除定时器

Vue项目中使用和清除定时器

作者:互联网

一、方法1

1)在首先在vue实例的data中定义定时器的名称:

export default{
  data(){
    timer:null  
  }
}

 

2)在方法(methods)或者页面初始化(mounted())的时候使用定时器

this.timer = setInterval(()=>{
  //需要做的事情
},1000);

 

3)然后在页面销毁的生命周期函数(beforeDestroy())中销毁定时器

export default{
  data(){
    timer:null  
  },
  beforeDestroy(){
    clearInterval(this.timer);
    this.timer = null;
  }
}

 

这种方法是可行的,但是也存在一定的问题:

1、vue实例中需要有这个定时器的实例,感觉有点多余;

2、 创建的定时器代码和销毁定时器的代码没有放在一起,通常很容易忘记去清理这个定时器,不容易维护;

 

二、方法2

直接在需要定时器的方法或者生命周期函数中声明并销毁

export default{
  methods:{
    fun1(){
      const timer = setInterval(()=>{
          //需要做的事情
         console.log(11111);
      },1000);
      this.$once('hook:beforeDestroy',()=>{
        clearInterval(timer);
        timer = null;
      })
    }
  }
}

这种方法创建和销毁放在一处,是比较好的方法

 

标签:定时器,销毁,清除,beforeDestroy,timer,Vue,export,null
来源: https://www.cnblogs.com/houchen/p/14675385.html