hookEvent还可以监听生命周期函数

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

通常我们都是这样写

 <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可以监听生命周期的用法

原文地址:https://www.cnblogs.com/yanyanliu/p/13584722.html