时间:2022-02-28 09:20:12 | 栏目:vue | 点击:次
我们会经常使用表格,如果数据量大就直接可以分页,但是不可避免的会出现一些需要一页要展示很多条的情况,或者不用分页。
这个时候如果纯展示还好一点,列表里如果加上可编辑,就会变得卡的不行,点个下拉框,下拉框好久才会弹出来。这样是十分影响用户使用。
刚开始加载时候获取10/20条数据(这个可以通过计算,每一行的高度/页面显示数据的高度,也可以固定数值),滚动的时候监听滚动条,根据滚动的距离来计算显示页面的数据。
列表的总高度
总数据长度 × 每一行的高度
如果只有页面显示的高度,就无法滚动获取新的数据
每一行的高度
如果是固定高度可以写死数值
如果是动态高度可以通过计算
滚动的偏移量
当前滚动的距离 - ( 当前滚动的距离 % 每一行的高度)
页面展示的数据的起始索引及结束索引
起始索引刚开始为0
滚动的过程中 起始索引 = Math.floor(当前滚动的距离 / 每一行的高度)
代码步骤
<div class="main-inner-content">
<el-table :data="visibleData" :style="{'min-height': gradingEditor ? listHeight+'px':'100%'}" id="dataTable">
</el-table>
</div>
computed: {
// //列表总高度
listHeight () {
// tableData 是获取接口的总数据
return this.tableData.length * this.itemSize;
},
// //偏移量对应的style
getTransform () {
return `translate3d(0,${this.startOffset}px,0)`;
},
//获取真实显示列表数据
visibleData () {
let tableBody = document.querySelector('#dataTable >.el-table__body-wrapper')
if (tableBody) {
tableBody.style.transform = this.getTransform
}
return this.tableData.slice(this.start, Math.min(this.end, this.tableData.length));
}
},
data() {
return {
tableData:[],
//偏移量
startOffset: 0,
//起始索引
start: 0,
//结束索引
end: null,
};
},
methods:{
handleScroll () {
// 这个是滚动的盒子,如果滚动的位置是table,这里也对应的改下就好了,还有偏移量赋值的地方
let scrollTop = document.getElementById('main-inner-content').scrollTop;
// //此时的开始索引
this.start = Math.floor(scrollTop / this.itemSize);
if (this.start < 0) this.start = 0;
// //此时的结束索引
this.end = this.start + 10;
// //此时的偏移量
this.startOffset = scrollTop - (scrollTop % this.itemSize);
this.startOffset = this.startOffset > this.itemSize ? this.startOffset - this.itemSize : 0;
}
},
mounted(){
window.addEventListener("scroll", this.handleScroll, true);
},
destroyed(){
window.removeEventListener('scroll', this.handleScroll, true) // 清除滚条滚动事件
}

页面滚动的时候一直只会加载十条数据
通过偏移量来确定页面展示
我是给整个el-table设置了总高度,然后给下面列表项的盒子设置的偏移量。如果页面是在不刷新的情况下需要重新获取数据(比如分页),一定要将数据初始化,否则页面会直接展示之前的数据,或者页面出现空白。
document.querySelector('#main-inner-content').scrollTop = 0
this.start = 0
this.startOffset = 0
this.end = this.start + 10;
let tableBody = document.querySelector('#dataTable >.el-table__body-wrapper')
tableBody.style.transform = this.getTransform
为了方便计算及使用,页面每一行的高度我采用的是固定高度的方式使用的是超出省略的方式,但是部署预发环境后会发现-webkit-box-orient: vertical这句代码直接就没有了,不显示。
解决办法:写行内样式style="-webkit-box-orient: vertical" 这样就可以了
.omit-text {
word-wrap: break-word;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
参考
https://juejin.cn/post/6844903982742110216#heading-4
https://codesandbox.io/s/virtuallist-1-forked-sd2xn?file=/src/components/VirtualList.vue:1487-1652