Vue 無限滾動(dòng)加載指令實(shí)現(xiàn)方法
也不存在什么加載咯, 就是一個(gè)判斷滾動(dòng)條是否到達(dá)瀏覽器底部了。 如果到了就觸發(fā)事件,米到就不處理。
計(jì)算公式提簡(jiǎn)單的 底部等于(0) = 滾動(dòng)條高度 - 滾動(dòng)條頂部距離 - 可視高度。 反正結(jié)果就是0。
一、獲取滾動(dòng)條位置
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é)點(diǎn)綁定滾動(dòng)事件
vue給body元素綁定滾動(dòng)條事件,真TMD草蛋。事件綁定上去了 媽的 就是不觸發(fā)事件。不知道什么鬼問題。
最后直接給根節(jié)點(diǎn)HTML綁定滾動(dòng)事件。
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); } }; } })();
三、注冊(cè)全局指令
/** * 降低事件執(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ā)頻率 } }) } });
四、實(shí)例:
<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/
總結(jié)
以上所述是小編給大家介紹的Vue 無限滾動(dòng)加載指令實(shí)現(xiàn)方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
Vue3.0 自己實(shí)現(xiàn)放大鏡效果案例講解
這篇文章主要介紹了Vue3.0 自己實(shí)現(xiàn)放大鏡效果案例講解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07vue.js通過自定義指令實(shí)現(xiàn)數(shù)據(jù)拉取更新的實(shí)現(xiàn)方法
數(shù)據(jù)拉取更新這個(gè)功能相信大家基本都見過,但是如果要做起來卻不止如何做起,所以這篇文章給大家分享了vue.js通過自定義指令實(shí)現(xiàn)的方法,閱讀本文需要對(duì)vue有一定理解,有需要的朋友們下面來一起看看吧。2016-10-10