您的当前位置:首页Vue 无限滚动加载指令实现方法

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

2020-11-27 来源:小侦探旅游网

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

计算公式提简单的   底部等于(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 无限滚动加载指令实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

显示全文