< div id = " app" >
< div class = " list-wrap" ref = " listWrap" @scroll = " scrollListener" >
< div class = " scroll-bar" ref = " scrollBar" > </ div>
< div class = " list" ref = " list" >
< div v-for = " item in showList" > {{item}}</ div>
</ div>
</ div>
</ div>
.list-wrap {
position : relative;
overflow-y : auto;
width : 200px;
margin : 100px auto;
box-sizing : border-box;
border : solid 1px #e2e2e2;
}
.list {
position : absolute;
top : 0;
left : 0;
width : 100%
}
.list>div {
border-bottom : solid 1px #e2e2e2;
line-height : 40px;
padding : 0 10px;
box-sizing : border-box;
}
< script src= "https://lib.baomitu.com/vue/2.6.12/vue.js" > < / script>
< script>
new Vue ( {
el: "#app" ,
data ( ) {
return {
list: [ ] ,
itemHeight: 41 ,
showNum: 10 ,
start: 0 ,
end: 10 ,
} ;
} ,
computed: {
showList ( ) {
return this . list. slice ( this . start, this . end) ;
} ,
} ,
mounted ( ) {
for ( let i = 0 ; i < 1000 ; i++ ) {
this . list. push ( "列表项" + i) ;
}
this . $refs. listWrap. style. height =
this . itemHeight * this . showNum + "px" ;
this . $refs. scrollBar. style. height =
this . itemHeight * this . list. length + "px" ;
} ,
methods: {
scrollListener ( ) {
let scrollTop = this . $refs. listWrap. scrollTop;
this . start = Math. floor ( scrollTop / this . itemHeight) ;
this . end = this . start + this . showNum;
this . $refs. list. style. top = this . start * this . itemHeight + "px" ;
} ,
} ,
} ) ;
< / script>