dom元素过多情况下懒加载(接口返回大量数据)
data() { return { // 渲染总数 total: 0, // 设置每次插入显示的DOM数量,根据情况自己设置 once: 20, // 当前已经渲染DOM的总数 countOfRender: 0, // 接口请求回来的完整数据 tempDataList:[], }; },
有bug,数量小于20条会报错,修改以后没解决,以后再说,用的话用下拉刷新就行,其他的有bug,dom多还是会卡
接口调用成功后调用,total 当前页面渲染总数
this.total = body.pageSize this.tempDataList =this.loop()
loop函数
loop() { // 每次只渲染once条数据 const temp = []; for (let i = 0; i < this.once; i++) { // 当DOM渲染完就退出 console.log('this.countOfRender',this.countOfRender) if (this.countOfRender >= this.total) return; temp.push(this.tempDataList[this.countOfRender]); this.countOfRender += 1; } this.dataList = this.dataList.concat(temp); },
监听滚动条和dom高度
scrollHandle() { // 滚动条底部位置 // window.innerHeight 为视口高度 contentBox和dataBody根据自己的页面判断 滚动条卷去高度 + 视口高度 let scrollHeight = document.getElementsByClassName('eventRigth')[0].scrollTop + window.innerHeight - 20 // 整个页面高度// 实际内容高度 + 内容距顶部距离 let realyHeight = document.getElementsByClassName('eventRigth')[0].offsetTop +document.getElementsByClassName('myEvent')[0].clientHeight // 是否触底,距离底部100px if(realyHeight - scrollHeight == 100){ this.loop() } },
绑定监听,销毁时移除监听
mounted(){ window.addEventListener("scroll", this.scrollHandle,true) }, beforeDestroy(){ window.removeEventListener("scroll", this.scrollHandle,true) }, destroyed(){ window.removeEventListener("scroll", this.scrollHandle,true) },