我们在实际工作中会遇到这样的问题:
应客户要求,某一个列表不允许分页。但是不分页的话,如果遇到大量的数据加载,不但后端响应速度变慢,前端的渲染效率也会降低,页面出现明显的卡顿。
那如何解决这个问题呢
我们可以用模拟分页,当滚动条滚动到底部时再次加载剩余的部分数据,触底加载,直到加载完成。
先看一个线上的演示示例:
https://code.juejin.cn/pen/7273420104565456953
开发思想参考:
https://blog.csdn.net/weixin_43340372/article/details/132601018?spm=1001.2014.3001.5501
代码
<div id="app"><el-table:data="tableData"height="300"row-key="id"bordersize="mini"v-el-table-lazyloading="lazyloading"><el-table-column prop="date" label="日期" width="180"> </el-table-column><el-table-column prop="name" label="姓名" width="180"> </el-table-column><el-table-column prop="address" label="地址"> </el-table-column></el-table>
</div><script>
// 伪造接口调用
class Api {#baseData = [{date: '2016-05-03',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}, {date: '2016-05-02',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}, {date: '2016-05-04',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}, {date: '2016-05-01',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}, {date: '2016-05-08',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}, {date: '2016-05-06',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}, {date: '2016-05-07',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}, {date: '2016-05-07',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}, {date: '2016-05-07',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}, {date: '2016-05-07',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}]getData(currentPage = 1, pageNumber = 10) {return new Promise(resolve => {setTimeout(() => {let data = [];if (currentPage > 1) {data = this.#baseData.map(item => ({...item, name: item.name + `currentPage-${currentPage}`, address: item.address + `currentPage-${currentPage}` }))} else {data = this.#baseData;}resolve(data);}, 1000)})}
}
const api = new Api();
// 全局注册组件
new Vue({el: '#app',directives: {"el-table-lazyloading": {bind(el, binding) {let SELECT_DOM = el.querySelector(".el-table__body-wrapper");console.log("SELECT_DOM",SELECT_DOM)SELECT_DOM.addEventListener("scroll", function () {let condition =this.scrollHeight - this.scrollTop <= this.clientHeight;if (condition) {binding.value();}});},},},data() {return {currentPage: 1,pageNumber: 10,value: "",tableData: [],};},methods: {async lazyloading() {this.loading = true;const data = await api.getData(this.currentPage);this.loading = false;this.tableData.push(...data);this.currentPage++;}},mounted() {this.lazyloading();}
})<style>
#app{padding: 10px;
}
</style>
</script>