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-element', {
     //元素选择,监听指定元素的滚动
    bind: async function (el, binding, vnode) {
     

    }
})
Vue.directive('lazyinit-condition', {
     //触发条件,指定条件下监听元素滚动
    bind: async function (el, binding, vnode) {
     

    }
})
Vue.directive('lazyinit-fromBottom', {
     //距离底部多少像素开始加载
    bind: async function (el, binding, vnode) {
     
        
    }
})

Vue.directive('lazyinit', {
     //定义加载方法
    bind: async function (el, binding, vnode) {
     
        let vm = vnode.context;
        await Vue.nextTick();
        let expression = {
     }//表达式
        let values = {
     }//值
        vnode.data.directives.map(d => {
     
            if(d.name.includes('lazyinit')){
     
                expression[d.name] = d.expression;
                values[d.name] = d.value;

            }
        })
        let condition = values['lazyinit-condition'];//触发条件
        if(condition!=undefined && !condition){
     
            return;
        }
        let element = values['lazyinit-element'];//元素选择
        if(element!=undefined && element){
     
            el = $(element)[0];
        }
        // console.log(el)
        $(el)
            .scroll(function () {
     
                if (vm[expression['lazyinit-done']]) {
     
                    // console.log("加载完毕");
                    return false;
                }
                //数据加载中
                if (vm[expression['lazyinit-loading']]) {
     
                    // console.log("加载中...")
                    return false;
                }

                var divHeight = $(el).height();
                var nScrollHeight = $(el)[0].scrollHeight - (values['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>

你可能感兴趣的:(Vue,html,js,vue,js,javascript,json,vue.js)