Vue 無限滾動加載指令實現(xiàn)方法
也不存在什么加載咯, 就是一個判斷滾動條是否到達瀏覽器底部了。 如果到了就觸發(fā)事件,米到就不處理。
計算公式提簡單的 底部等于(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;
}
}
二、給根節(jié)點綁定滾動事件
vue給body元素綁定滾動條事件,真TMD草蛋。事件綁定上去了 媽的 就是不觸發(fā)事件。不知道什么鬼問題。
最后直接給根節(jié)點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);
}
};
}
})();
三、注冊全局指令
/**
* 降低事件執(zhí)行頻率
*/
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就觸發(fā)
downsampler(50, binding.value); // 降低觸發(fā)頻率
}
})
}
});
四、實例:
<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 無限滾動加載指令實現(xiàn)方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關文章
vue.js通過自定義指令實現(xiàn)數(shù)據(jù)拉取更新的實現(xiàn)方法
數(shù)據(jù)拉取更新這個功能相信大家基本都見過,但是如果要做起來卻不止如何做起,所以這篇文章給大家分享了vue.js通過自定義指令實現(xiàn)的方法,閱讀本文需要對vue有一定理解,有需要的朋友們下面來一起看看吧。2016-10-10

