<template>
<div
ref="vList"
class="vl-container"
:style="{ height: clientHeight + 'px' }"
>
<div class="vl-wrap" :style="{ height: vlHeight + 'px' }">
<div
class="vl-item"
:style="{
height: rowHeight + 'px',
lineHeight: rowHeight + 'px',
top: setTop(index) + 'px',
}"
v-for="(v, index) in visibleData"
:key="v.index"
>
<template v-if="$scopedSlots.default">
<slot :data="v"></slot>
</template>
<template v-else>{{ v.name }}</template>
</div>
</div>
</div>
</template>
<script>
import { debounce } from "@/utils";
export default {
props: {
bufferCount: {
type: Number,
default: 2,
},
data: {
type: Array,
default: () => {
return Array(1000)
.fill("")
.map((v, i) => {
return { name: i + 1, age: 11 };
});
},
},
clientHeight: {
type: Number,
default: 300,
},
rowHeight: {
type: Number,
default: 50,
},
},
data() {
return {
pageSize: 0,
scrollTop: 0,
offsetIndex: 0,
};
},
computed: {
vlHeight() {
return this.data.length * this.rowHeight;
},
visibleData() {
this.pageSize = Math.ceil(this.clientHeight / this.rowHeight);
this.offsetIndex = Math.floor(this.scrollTop / this.rowHeight);
let startIndex =
this.offsetIndex >= this.bufferCount
? this.offsetIndex - this.bufferCount
: 0;
let lastIndex = this.pageSize + this.offsetIndex + this.bufferCount;
let endIndex =
lastIndex > this.data.length ? this.data.length : lastIndex;
return this.data.slice(startIndex, endIndex);
},
},
mounted() {
this.$refs.vList.addEventListener(
"scroll",
debounce(() => {
this.scrollTop = this.$refs.vList.scrollTop;
}, 10),
false
);
},
methods: {
setTop(index) {
if (this.offsetIndex > this.bufferCount) {
return this.rowHeight * (index + this.offsetIndex - this.bufferCount);
} else {
return this.rowHeight * index;
}
},
},
};
</script>
<style scoped>
.vl-container {
border: 2px solid #0094ff;
overflow: auto;
}
.vl-container > .vl-wrap {
overflow: hidden;
position: relative;
}
.vl-container > .vl-wrap > .vl-item {
position: absolute;
width: 100%;
box-sizing: border-box;
border-bottom: 1px dotted red;
background-color: #e7e7be;
}
</style>