懒加载-虚拟列表
<template>
<div :style="{height: `${contentHeight}px`}" class="content_box" @scroll="scroll">
<!--这层div是为了把高度撑开,让滚动条出现,height值为所有数据总高-->
<div :style="{'height': `${itemHeight*(listAll.length)}px`, 'position': 'relative'}">
<!--可视区域里所有数据的渲染区域-->
<div :style="{'position': 'absolute', 'top': `${top}px`}">
<!--单条数据渲染区域-->
<div v-for="(item,index) in showList" :key="index" class="item">
{{item}}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "list",
data(){
return{
listAll: [],
showList: [],
contentHeight: 500,
itemHeight: 30,
showNum: 0,
top: 0,
scrollTop: 0,
startIndex: 0,
endIndex: 0,
}
},
methods:{
getList(){
for(let i=0;i<100000;i++){
this.listAll.push(`我是第${i}条数据呀`)
}
},
getShowList(){
this.showNum = Math.ceil(this.contentHeight/this.itemHeight);
this.startIndex = Math.floor(this.scrollTop/this.itemHeight);
this.endIndex = this.startIndex + this.showNum;
this.showList = this.listAll.slice(this.startIndex, this.endIndex)
const offsetY = this.scrollTop - (this.scrollTop % this.itemHeight);
this.top = offsetY;
},
scroll(){
this.scrollTop = document.querySelector('.content_box').scrollTop;
this.getShowList();
}
},
mounted() {
this.getList();
this.scroll();
}
}
</script>
<style scoped>
.content_box{
overflow: auto;
width: 700px;
border: 1px solid red;
}
.item{
height:30px;
padding: 5px;
color: #666;
box-sizing: border-box;
}
</style>
https://mp.weixin.qq.com/s/A-M_JLSt0NeO9F9lsYjN7Q