0
点赞
收藏
分享

微信扫一扫

vue项目中对于Scroll事件的节流优化

芝婵 2022-02-16 阅读 70
  methods: {
    throttle(fn, wait) { // 封装函数进行节流
      var timer = null;
      return function () {
        var context = this;
        var args = arguments;
        if (!timer) {
          timer = setTimeout(function () {
            fn.apply(context, args);
            timer = null;
          }, wait);
        }
      };
    },
    handle() { // 功能代码
      let scroll_height = document.documentElement.scrollTop || document.body.scrollTop
      scroll_height>=120 ? this.show = true : this.show = false
    }
  },
  mounted() { 
   window.addEventListener("scroll", this.throttle(this.handle, 300));
  },
  destroyed(){  // 这里运用毁灭生命周期 , 避免资源泄露和浪费
    window.removeEventListener("scroll", this.throttle(),false);
  },

举报

相关推荐

0 条评论