<template>
<div class="scroll-container" ref="scrollContainer" @scroll="handleScroll">
<div v-for="item in visibleItems" :key="item.id" class="item">{{ item.name }}</div>
<div v-if="loading" class="loading">Loading...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // 所有数据
visibleItems: [], // 可见的数据
loading: false, // 是否正在加载数据
pageSize: 10, // 每页加载的数据量
currentPage: 1, // 当前页数
totalItems: 0, // 总数据量
};
},
mounted() {
// 初始化数据
this.fetchData();
},
methods: {
fetchData() {
// 模拟异步获取数据
this.loading = true;
setTimeout(() => {
// 假设从服务器获取数据
const data = this.getMoreData();
this.items = this.items.concat(data);
this.totalItems = this.items.length;
this.loading = false;
this.updateVisibleItems();
}, 1000);
},
updateVisibleItems() {
// 根据当前页数和每页数量,更新可见的数据
const startIndex = (this.currentPage - 1) * this.pageSize;
const endIndex = startIndex + this.pageSize;
this.visibleItems = this.items.slice(startIndex, endIndex);
},
handleScroll() {
// 检测滚动位置,加载更多数据
const container = this.$refs.scrollContainer;
const containerHeight = container.offsetHeight;
const contentHeight = container.scrollHeight;
const scrollOffset = container.scrollTop;
if (contentHeight - containerHeight - scrollOffset < 200 && !this.loading) {
// 滚动到底部附近,加载更多数据
this.currentPage++;
this.fetchData();
}
},
getMoreData() {
// 模拟获取更多数据的方法
const newData = [];
for (let i = 0; i < this.pageSize; i++) {
const id = this.items.length + i + 1;
const name = `Item ${id}`;
newData.push({ id, name });
}
return newData;
},
},
};
</script>
<style scoped>
.scroll-container {
height: 300px;
overflow-y: auto;
}
.item {
margin: 10px;
padding: 20px;
background-color: #f0f0f0;
}
.loading {
text-align: center;
margin: 10px;
}
</style>