开发项目时,有时候一页的数据过多,但是只想展示可视框列表时,滚动时再加载出来
<template>
<div>
<div class="list" id="scroll-list" :style="{ height: contentHeight + 'px' }" ref="contentRef" @scroll="scrollList">
<div class="scroll-bar" ref="scrollBar">
<!-- 整个长列表的总长度 -->
</div>
<div class="scroll-list" ref="scrollListRef" :style="{ transform: `translate3d(0,${offset}px,0)` }">
<!-- 可视区的列表 -->
<div class="item" ref="container" v-for="(item, idx) in showList" :key="idx">
<slot :items="item"></slot>
<!-- <slot name="content1"></slot> -->
</div>
</div>
<!-- <div class="loading" v-show="isShow">loading...</div> -->
</div>
</div>
</template>
<script>
export default {
name: "VisibleScroll",
data() {
return {
startIndex: 0,
endIndex: 10,
offset: 0,
pageLimit: 0,
isShow: false,
};
},
props: {
// list: {
// type: Array,
// required: true,
// default: () => [],
// twoWays: true,
// },
originList: {
type: Array,
default: () => [],
},
listItemHeight: {
type: Number,
default: 0,
},
contentHeight: {
type: Number,
default: 0,
},
// offsetY: {
// type: Number,
// default: null,
// },
activeClassName: {
type: String,
default: "",
},
},
watch: {
// offsetY(index) {
// if (!this.activeClassName) return;
// let i = this.contentHeight / this.listItemHeight;
// // 下一个dom更新的时候,获取第i个元素,执行自动滚动动作
// this.$nextTick((_) => {
// // ?.是es2020的链判断运算符
// let targetChild = this.$refs.container[i]?.children[0] || "";
// // let targetChild = this.$refs.container[i].children[0] || "";
// if (targetChild && targetChild.className.includes(this.activeClassName)) {
// this.$refs.contentRef.scrollTop = index * this.listItemHeight;
// }
// });
// },
},
computed: {
showList() {
// console.log("startIndex", this.startIndex);
// console.log("endIndex", this.endIndex);
return this.originList.slice(this.startIndex, this.endIndex);
},
},
methods: {
scrollList(e) {
// console.log(e);
let currentScrollTop = e.target.scrollTop;
// console.log(currentScrollTop);
this.startIndex = Math.floor(currentScrollTop / this.listItemHeight);
this.endIndex = this.startIndex + this.pageLimit + 1;
this.offset = this.startIndex * this.listItemHeight;
},
},
created() {},
mounted() {
this.pageLimit = Math.ceil(this.contentHeight / this.listItemHeight);
console.log(this.pageLimit);
this.$refs.scrollBar.style.height = this.listItemHeight * this.originList.length + "px";
// + 1是为了多加载一个,让他滚动的时候看起来没有空位
this.endIndex = this.pageLimit + 1;
this.app.$emit("scrollBottom");
},
};
</script>
<style lang="scss" scoped>
.list {
overflow: auto;
position: relative;
}
.scroll-list {
position: absolute;
left: 0;
top: 0;
width: 100%;
transform: translate3d(0, 0, 0);
padding: 0;
margin: 0;
list-style: none;
}
</style>
使用时:
<visible-scroll :originList="devList" :listItemHeight="20" :contentHeight="418">
<template v-slot="slotProp">
{{ slotProp.items.name }}
</template>
</visible-scroll>