1. 基础构造
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c645b0156d60cbeefd511e01f580b701.png)
2. 实践
<style>
.viewport{
overflow-y: scroll;
position: relative;
border: 1px solid gray;
};
.scrollbar{
}
.list{
position: absolute;
left: 50%;
top: 0;
}
.list-row{
height: 20px;
}
</style>
<div id="app">
<div ref="viewport" class="viewport" @scroll="onScroll">
<div ref="scrollbar" class="scrollbar" ></div>
<div class="list" :style="{ transform:`translateY(${offset}px)` }">
<div class="list-row" :style="{height:height+'px'}" v-for="(item) in showList">
{{ item }}
</div>
</div>
</div>
</div>
const bigList = new Array(100000).fill(null).map((value, index) => index + 1);
new Vue({
methods: {
onScroll(){
this.offset = this.$refs.viewport.scrollTop;
this.start = Math.round(this.offset/this.height);
this.end = this.start+this.viewCount;
}
},
mounted() {
this.$refs.viewport.style.height = (this.viewCount * this.height) + 'px';
this.$refs.scrollbar.style.height = (this.list.length * this.height) + 'px';
},
computed:{
showList(){
return this.list.slice(this.start,this.end)
}
},
el: "#app",
data() {
return {
list: bigList,
start: 0,
end: 20,
viewCount: 20,
height: 20,
offset: 0,
};
},
});