平时在做项目的时候,一般会遇到在某个时候开启定时器,在离开这个页面的时候卸载掉这个定时器

通常我们都是这样写

 <button @click="onClick">定时器开启</button>

 methods: {
    onClick() {
      this.time = setInterval(() => {
        console.log(2222)
      }, 1000);
    }
  },

destroyed () {
    clearInterval(this.time)
  }

这样写一点毛病没有,但一般项目里每个页面都会有很多方法,就导致你在点击的这个方法里开启定时器,你就还要去找这个定时器在哪里卸载,不宜读,所以就用到了hook这个东西

 <button @click="onClick">定时器开启</button>

 methods: {
    onClick() {
      this.time = setInterval(() => {
        console.log(2222)
      }, 1000);

      this.$on("hook:destroyed", () => {
        clearInterval(this.time);
      });
    }
  },

这样就一目了然,开启定时器和关闭定时器都写在一块,也是利用了hook可以监听生命周期的用法

相关文章:

  • 2021-10-22
  • 2022-12-23
  • 2022-12-23
  • 2021-04-30
  • 2021-05-15
猜你喜欢
  • 2021-06-20
  • 2021-10-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-10
相关资源
相似解决方案