vue中使用$.once(‘hook:beforeDestory’,() => {})清理定时器

今天看代码看到了一个自己没有用过的

export default {
  data() {
    return {
      //下拉浮动标志的显示控制
      showFlag: true
    };
  },
  methods: {
    //点击事件 实现点击浮动下拉图标,平滑滑动到主页开头部分(也是侧边栏的头)
    moveToHome() {
      //目标元素距离页面顶部的距离,在这里是恒定值
      let total = document.getElementById("blog_main").offsetTop;
      move(total);
    }
  },
  created() {
    //定时器
    const timer = setInterval(() => {
      this.showFlag = !this.showFlag;
    }, 1000);
    this.$once("hook:beforeDestroy", () => {
      clearInterval(timer);
    });
  },
  mounted() {},
  components: {
    Typer
  }
};

在vue项目清理定时器,通常有两种方法
方法一:
1、首先在vue实例的data中定义定时器的名称,
2、在方法(methods)或者页面初始化(mounted())的时候使用定时器
3、然后在页面销毁的生命周期函数(beforeDestroy())中销毁定时器
实现代码:

export default{
  data(){
    timer:null  
  },
  mounted(){
	  this.timer = setInterval(()=>{
	  //具体执行内容
	  console.log('1');
	},1000);
  }
  beforeDestory(){
    clearInterval(this.timer);
    this.timer = null;
  }
}

注: 第一种方法存在的问题是:
1、vue实例中需要有这个定时器的实例,感觉有点多余;
2、 创建的定时器代码和销毁定时器的代码没有放在一起,通常很容易忘记去清理这个定时器,不容易维护;

因此,更推荐第二种方法,使用this.$once(‘hook:beforeDestory’,()=>{});

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

export default{
  methods:{
    fun1(){
      const timer = setInterval(()=>{
      	//具体执行代码
        console.log('1');
      },1000);
      this.$once('hook:beforeDestory',()=>{
        clearInterval(timer);
        timer = null;
      })
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/smart-girl/p/13396982.html