也不存在什么加載咯, 就是一個判斷滾動條是否到達瀏覽器底部了。 如果到了就觸發事件,米到就不處理。
計算公式提簡單的 底部等于(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 無限滾動加載指令實現方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對錯新站長站網站的支持!
新聞熱點
疑難解答
圖片精選