vue 2表格滚动加载
自定义指令
// 表格下拉滚动加载更多
Vue.directive('loadmore', {
bind(el, binding) {
// 节流函数
const throttle = (fn, wait = 300) => {
let inThrottle, lastFn, lastTime;
return function() {
const context = this,
args = arguments;
if (!inThrottle) {
fn.apply(context, args);
lastTime = Date.now();
inThrottle = true;
} else {
clearTimeout(lastFn);
lastFn = setTimeout(function() {
if (Date.now() - lastTime >= wait) {
fn.apply(context, args);
lastTime = Date.now();
}
}, Math.max(wait - (Date.now() - lastTime), 0));
}
};
};
const selectWrap = el.querySelector('.el-table__body-wrapper');
if (selectWrap) {
const handleScroll = throttle(function() {
let sign = 100;
const scrollDistance = this.scrollHeight - this.scrollTop - this.clientHeight;
if (scrollDistance <= sign) {
// 触发加载更多
binding.value();
}
}, 300);
// 使用passive监听器提高滚动性能
selectWrap.addEventListener('scroll', handleScroll, { passive: true });
}
}
});
<el-table
v-loading="loading"
:data="rankingData"
v-loadmore="loadMore"
height="525"
style="width: 100%;"
border
>
<el-table-column
prop="ranking"
label="排名"
width="100"
align="center"
/>
<el-table-column
prop="loginTimes"
label="登录次数"
min-width="100"
align="center"
></el-table-column>
</el-table>
// 滚动加载
loadMore() {
if (this.total > this.rankingData.length) {
this.query.pageNum++;
this.getRankingList();
}
}
// 去除重复数据
const dataList = data.result;
if (dataList.length) {
// 使用 Set 来去重
const appIds = new Set(this.rankingData.map(data => data.appId));
const notExistData = dataList.filter(data =>
!appIds.has(data.appId));
const rankingData = [...this.rankingData, ...notExistData];
// 升序排列
this.rankingData = rankingData.sort((a, b) =>
a.ranking - b.ranking);
this.total = data.count;
this.showMoreHint = this.total > this.rankingData.length;
}