实现效果:
写在前面:
当数据量过大时,我们如果直接将数据渲染到DOM上的话,那么时间会很长,页面也会卡顿,这时候就需要用到懒加载,当页面滑动到底部时候,再把数据渲染到DOM上
实现步骤:
1.定义三个参数
// 懒加载
visibleItems: [], // 可见的数据数组
batchSize: 20, // 每次加载的数量
currentBatch: 1, // 当前渲染的批次
2.定义一个加载更多的函数,使得数据可以按批次渲染
// 加载更多
loadMore() {
console.log('加载更多')
const start = this.currentBatch * this.batchSize;
const end = start + this.batchSize;
this.visibleItems = this.visibleItems.concat(this.allMedicalList.slice(start, end));
this.currentBatch++;
},
3.绑定滚动监听事件
<div class="content" ref="scrollview" @mousewheel="scrollChange">
mounted() {
// 获取指定元素
const scrollview = this.$refs['scrollview']
// 添加滚动监听,该滚动监听了拖拽滚动条
// 尾部的 true 最好加上,我这边测试没加 true ,拖拽滚动条无法监听到滚动,加上则可以监听到拖拽滚动条滚动回调
scrollview.addEventListener('scroll', this.handleScroll, true)
},
// 判断是否滑动到页面底部
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target
// console.log(scrollTop, clientHeight, scrollHeight)
if (scrollTop + clientHeight === scrollHeight) {
// alert('滚动到底部啦')
console.log('滚动到底部啦')
this.loadMore()
}
},
scrollChange() {
console.log('滚动中')
},