vue 2.x 之怎么绑定、解绑节流函数

很多人都在项目里使用过节流或者防抖函数,但是绑定的时候很简单,但是解绑失败了找不到原因,其实非常简单,绑定和解绑只要是同一个函数就没有问题了。
只要紧记绑定和解绑的事件是同一个就行了,如果不是一个,就单写成一个函数

export default {
  mounted() {
    //执行绑定函数事件
    this.addScrollData();
  },
  methods: {
    // 滚动加载数据
    getScrollData: utils.throttle(function() {
      // 节流getScrollTop
        this.getScrollTop();
    },300),
    // 绑定滚动加载数据事件
    addScrollData(){
      //当然你也可以把上面的这个getScrollData写在这个函数里
      this.getScrollData = utils.throttle(function() {
        // 节流getScrollTop
          this.getScrollTop();
      },300);

      // 绑定滚动加载数据事件
      window.addEventListener('scroll', this.getScrollData);
    }
  },
  //离开路由和组件销毁选择适合项目写一种解绑即可
  // 离开路由之前
  beforeRouteLeave(to, from, next){
    // 解绑scroll事件
    window.removeEventListener('scroll', this.getScrollData);
    next();
  },
  //组件销毁之前
  beforeDestroy () {
    // 解绑scroll事件
    window.removeEventListener('scroll', this.getScrollData);
  },
};
原文地址:https://www.cnblogs.com/jiaoshou/p/13706969.html