使用 Vue 实现一个简单的虚拟滚动
虚拟滚动是一种优化长列表性能的技术,它通过动态渲染可视区域内的列表项,避免一次性渲染所有项导致的性能问题。具体来说,虚拟滚动将可视区域内和周围的列表项渲染出来,并且在用户滚动列表时,动态地添加和删除项,从而保证渲染的元素数量尽可能少。
实现虚拟滚动的方式有多种,其中最简单的方式是基于浏览器自带的 scroll 事件和 DOM 元素操作实现,下面是一个 Vue 实现一个简单的虚拟滚动的代码示例:
设计思路
-
使用
padding占用虚拟空间,避免频繁操作 DOM。 -
配置参数包括:单个元素高度
height、容器高度mainHeight、预加载临界值数量preLoadNum、数据源listResource。 -
变量
top(代表顶部不加载的 DOM 元素个数)和bottom(代表底部不加载的 DOM 元素个数)与paddingTop和paddingBottom相关联。 -
预加载数量需要考虑顶部和底部的,也就是说预加载的数量最多只能是
2*preLoadNum。 -
scroll 事件和 DOM 元素操作实现,dom操作交个vue去实现了
实现代码
<template>
<div class="main" :style="{ height: mainHeight + 'px' }" @scroll="divScroll($event)">
<div :style="{ paddingTop, paddingBottom }" class="content" ref="content">
<div :style="{ height: height + 'px' }" v-for="item in list" :key="item">div>
div>
div>
template>
<script>1
export default {
data() {
return {
scrollTop: 0,
top: 0,
bottom: 0,
}
},
props: {
listResource: { //数据源
default: () => [new Array(100)].map((item, index) => index)
},
mainHeight: { // 容器高度
default: 500
},
height: { // 元素高度
default: 50
},
preLoadNum: { //预加载数量
default: 10
},
},
computed: {
paddingTop() {
return this.top * this.height + 'px';
},
paddingBottom() {
return this.bottom * this.height + 'px';
},
showNums() { // 可视区域最多可展示数量
return Math.ceil(this.mainHeight / this.height);
},
list() { // 需要渲染的列表
return this.listResource.slice(this.top, this.listResource.length - this.bottom)
},
},
methods: {
divScroll(event) {
const scrollTop = Math.floor(event.target.scrollTop / this.height)
if (scrollTop !== this.scrollTop) {
this.scrollTop = scrollTop;
this.top = this.getTop();
this.bottom = this.getBottom();
console.log(this.scrollTop, this.top, this.bottom)
}
},
getTop() { // 临界条件就是顶部可预加载的数量不足 preLoadNum
if (this.scrollTop > this.preLoadNum) {
return this.scrollTop - this.preLoadNum;
} else {
return 0;
}
},
getBottom() { // 临界条件就是底部可预加载的数量不足 preLoadNum
if (this.listResource.length - this.scrollTop - this.showNums > this.preLoadNum) {
return this.listResource.length - this.showNums - this.preLoadNum - this.scrollTop;
} else {
return 0;
}
}
},
created() {
this.bottom = this.getBottom();
}
}
script>
<style scoped>
.main {
overflow: auto;
}
.content {
width: 100%;
}
.content > div:nth-child(2n) {
background-color: #cccccc;
}
style>
上面代码只是实现了一些皮毛,还有极大的优化空间。


