本来用的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>