Vue 无限滚动加载指令

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

计算公式提简单的   底部等于(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/

猜你喜欢

转载自www.cnblogs.com/whnba/p/10775118.html