1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| <template> <div :style="{ height: `${contentHeight}px` }" class="content_box" @scroll="scroll" > <div :style="{ height: `${itemHeight * listAll.length}px`, position: 'relative', }" > <div :style="{ position: 'absolute', top: `${top}px` }"> <div v-for="(item, index) in showList" :key="index" class="item"> {{ item }} </div> </div> </div> </div> </template>
<script> export default { name: "list", data() { return { listAll: [], showList: [], contentHeight: 500, itemHeight: 30, showNum: 0, top: 0, scrollTop: 0, startIndex: 0, endIndex: 0, }; }, methods: { getList() { for (let i = 0; i < 100000; i++) { this.listAll.push(`我是第${i}条数据呀`); } }, getShowList() { this.showNum = Math.ceil(this.contentHeight / this.itemHeight); this.startIndex = Math.floor(this.scrollTop / this.itemHeight); this.endIndex = this.startIndex + this.showNum; this.showList = this.listAll.slice(this.startIndex, this.endIndex); const offsetY = this.scrollTop - (this.scrollTop % this.itemHeight); this.top = offsetY; }, scroll() { this.scrollTop = document.querySelector(".content_box").scrollTop; this.getShowList(); }, }, mounted() { this.getList(); this.scroll(); }, }; </script>
<style scoped> .content_box { overflow: auto; width: 700px; border: 1px solid red; }
.item { height: 30px; padding: 5px; color: #666; box-sizing: border-box; } </style>
|