Vue滾動懶加載自寫自定義指令

本來用的ElementUI的v-infinite-scroll發現並不是很好用所以自己寫了一個
實現了滾動到底部進行加載的功能
直接上代碼:

//滾動懶加載
Vue.directive('lazyinit-done', {//加載完成狀態變量
    bind: async function (el, binding, vnode) {

    }
})

Vue.directive('lazyinit-loading', {//加載中狀態變量
    bind: async function (el, binding, vnode) {

    }
})
Vue.directive('lazyinit-fromBottom', {//距離底部多少像素開始加載
    bind: async function (el, binding, vnode) {
        console.log(binding)
    }
})

Vue.directive('lazyinit', {//定義加載方法
    bind: async function (el, binding, vnode) {
        let vm = vnode.context;
        await Vue.nextTick();
        let json = {}
        vnode.data.directives.map(d => {
            json[d.name] = d.expression;
        })
        //console.log(el)
        $(el)
            .scroll(function () {
                if (vm[json['lazyinit-done']]) {
                    // console.log("加載完畢");
                    return false;
                }
                //數據加載中
                if (vm[json['lazyinit-loading']]) {
                    // console.log("加載中...")
                    return false;
                }

                var divHeight = $(el).height();
                var nScrollHeight = $(el)[0].scrollHeight - (vm[json['lazyinit-fromBottom']] || 10);
                var nScrollTop = $(el)[0].scrollTop;
                // console.log(nScrollTop, divHeight, nScrollHeight);
                // console.log(nScrollTop + divHeight >= nScrollHeight);
                if (nScrollTop + divHeight >= nScrollHeight) {
                    // console.log("到達底部了");
                    binding.value.call(vm)

                }
            });
    }
})

用法:
在需要滾動加載的有滾動條的元素中添加相應的指令
:

 <div v-lazyinit="load" v-lazyinit-done="done" v-lazyinit-loading="loading" v-if="dataList.length!=0" class="content">
    <template v-for="(d,i) in dataList">
    	<div :key="i">{{i}}</div>
    </template>
    //...加載更多按鈕
 </div>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章