<template>
<div class="scroll-main" @scroll="fn" ref="scrollBox">
<div :style="{paddingTop:startNum * itemHeight + 'px',paddingBottom:(allHX.length - endNum) * itemHeight + 'px'}">
<div v-for="(item, index) in showHX" :key="item.id" class="item" :style="{height: (itemHeight - 2) + 'px'}">
<span>{{item.id}}-{{item.msg}}</span>
<span @click="deleteItem(index)">删除</span>
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
allHX: [],
startNum: 0,
boxHeight: 0,
fn: this.debounce(this.startScroll, 100),
wishList: ['洗脚', '按摩', '给零花钱', '做饭', '买车', '买房', '做项目', '带娃', '应付丈母娘']
};
},
props: {
itemHeight: {
type: String,
default: '100'
}
},
created () {
this.getMock(100000);
},
mounted () {
this.getBoxHeight();
},
methods: {
getMock (count) {
for (let i = 0; i < count; i++) {
this.allHX.push({
id: `${i}号`,
msg: `${this.wishList[i % 9]}`,
});
}
},
getBoxHeight () {
// 获取可视区域的高度
this.boxHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
},
startScroll () {
let target = Math.floor(this.$refs.scrollBox.scrollTop / this.itemHeight);
if (target > this.allHX.length - this.pageNum) {
this.startNum = this.allHX.length - this.pageNum;
return
}
this.startNum = target;
},
deleteItem (index) {
this.allHX.splice(this.startNum + index, 1);
},
debounce (fun, wait) {
let timer = null;
return function () {
if (timer !== null) clearTimeout(timer);
timer = setTimeout(fun, wait);
}
}
},
computed: {
pageNum () {
return Math.ceil(this.boxHeight / this.itemHeight);
},
endNum () {
return this.startNum + this.pageNum;
},
showHX () {
return this.allHX.slice(this.startNum, this.endNum);
}
}
};
</script>
<style scoped>
.scroll-main {
height: 100%;
overflow: scroll;
overflow-x: hidden;
}
.item {
display: flex;
justify-content: space-between;
align-items: center;
border: 1px solid red;
padding: 0 20px;
}
</style>
vue - 虚拟列表实现
最新推荐文章于 2024-04-21 16:18:59 发布