zoukankan      html  css  js  c++  java
  • 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可以监听生命周期的用法

  • 相关阅读:
    集合
    字典
    列表
    事件兼容性封装
    E5中遍历数组的方法
    canvas绘制三等分饼型图
    canvas制作刮刮乐案例
    canvas绘制饼型图
    javascript中手风琴特效
    javascript中client()兼容性封装
  • 原文地址:https://www.cnblogs.com/yanyanliu/p/13584722.html
Copyright © 2011-2022 走看看