我正在尝试为具有可变高度的项目实现虚拟滚动。到目前为止,我见过的每个其他实现都要求您在声明模块时指定高度。
我的列表实现如下:
<div
class="main"
ref="main"
@scroll="handleScroll"
>
<div :style="{
'margin-top':padTop+'px',
'margin-bottom':padBottom()+'px'
}">
<div v-for="i in maxDisplayed">
<slot :name="'s-' + (i + startIndex - 1)">{{i + startIndex - 1}}</slot>
</div>
</div>
</div>
handleScroll
函数(失败的函数)是:
handleScroll (e) {
if (!this.$refs.main || this.$refs.main.scrollTop == undefined) return; //can't calculate if there's nothing displayed
// top of the items list container relative to the page top
let mainTop = this.$refs.main.getBoundingClientRect().top;
// bottom position of the first "displayed" item
let itemTop = this.$refs.main.children[0].children[0].children[0].getBoundingClientRect().top;
let itemBottom = this.$refs.main.children[0].children[0].children[0].getBoundingClientRect().bottom;
if (itemBottom < mainTop && (Object.keys(this.$slots).length > (this.startIndex + this.maxDisplayed))) {
this.startIndex ++;
this.heights.push(this.$refs.main.children[0].children[0].children[0].clientHeight);
}
else if (itemTop > mainTop && (this.startIndex > 0)) {
this.heights.pop();
this.startIndex = Math.max(this.startIndex - 1, 0);
}
},
到目前为止,当用户滚动相对较慢时,我的代码工作正常。但是当您快速滚动列表时它会失败。我怀疑这与它无法捕捉所有飞过滚动窗口的孩子有关。任何帮助将不胜感激。