Vue 无限滚动加载指令实现方法

2019-11-12,,

也不存在什么加载咯, 就是一个判断滚动条是否到达浏览器底部了。 如果到了就触发事件,米到就不处理。

计算公式提简单的   底部等于(0) =  滚动条高度 - 滚动条顶部距离 - 可视高度。  反正结果就是0。

一、获取滚动条位置

class Scroll {
  static get top() {
    return Math.max(document.documentElement.scrollTop || document.body.scrollTop);
  }
  static get clientHeight() {
    return Math.max(document.documentElement.clientHeight || document.body.clientHeight);
  }
  static get clientWidth() {
    return Math.max(document.documentElement.clientWidth || document.body.clientWidth);
  }
  static get height() {
    return Math.max(document.documentElement.scrollHeight || document.body.scrollHeight);
  }
  static get width() {
    return Math.max(document.documentElement.scrollWidth || document.body.scrollWidth);
  }
  static get bottom() {
    return Scroll.height - Scroll.clientHeight - Scroll.top;
  }
}

二、给根节点绑定滚动事件

vue给body元素绑定滚动条事件,真TMD草蛋。事件绑定上去了 妈的 就是不触发事件。不知道什么鬼问题。

最后直接给根节点HTML绑定滚动事件。

const on = (function () {
  if (document.addEventListener) {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.addEventListener(event, handler, false);
      }
    };
  } else {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.attachEvent('on' + event, handler);
      }
    };
  }
})();

三、注册全局指令

/**
 * 降低事件执行频率
 */
const downsampler = (function () {
  let result = null;
  return function (time, func) {
    if (!result) {
      result = setTimeout(function () {
        func();
        result = null;
      }, time);
    }
  }
})();

Vue.directive("infinite-scroll", {
  bind(el, binding, vnode) {
    on(window, 'scroll', function () {
      if (typeof binding.value === "function" && Scroll.bottom <= 50) {  // 小于50就触发
        downsampler(50, binding.value); // 降低触发频率
      }
    })
  }
});

四、实例:

<div class="app" v-infinite-scroll="coupon">
    <template v-for="item in goods">
      <p>{{item}}</p>
   </template>
</div>
    let v = new Vue({
      el: ".app",
      data(){
        return {
          goods:[]
        }
      },
      methods: {
        coupon() {
          this.goods.push("你呵呵")
        }
      }
    })

演示地址:http://whnba.gitee.io/tkspa/

总结

以上所述是小编给大家介绍的Vue 无限滚动加载指令实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对北冥有鱼网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

  • vue中获取滚动table的可视页面宽度调整表头与列对齐(每列宽度不都相同)
  • vue 实现滚动到底部翻页效果(pc端)
  • vue滚动tab跟随切换效果
  • Vue.js+cube-ui(Scroll组件)实现类似头条效果的横向滚动导航条
  • 基于vue实现滚动条滚动到指定位置对应位置数字进行tween特效
  • vue使用keep-alive保持滚动条位置的实现方法
  • vue的滚动条插件实现代码

《Vue 无限滚动加载指令实现方法.doc》

下载本文的Word格式文档,以方便收藏与打印。