一、实现效果
二、实现思路
使用滚动事件监听器来检测用户是否滚动到底部,然后加载更多数据
- 监听滚动事件。
- 检测用户是否滚动到底部。
- 加载更多数据。
三、案例代码
<div class="drawer-content">
<div ref="loadMoreTrigger" class="load-more-trigger"></div>
<div v-if="isLoading" class="loading-button">
<button type="primary" loading>加载中...</button>
</div>
</div>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
const isLoading = ref(false);
const page = ref(1);
const loadMoreData = async () => {
if (isLoading.value) return;
isLoading.value = true;
// 模拟异步加载数据
setTimeout(() => {
const newItems: any = props.chartTableData
?.slice(0, 10)
.map((item) => ({ ...item, id: item.id + page.value * 100 }));
cardList.value = [...cardList.value, ...newItems];
page.value += 1;
isLoading.value = false;
}, 1000);
};
const handleScroll = () => {
const drawerContent = document.querySelector('.drawer-content');
if (drawerContent) {
const { scrollTop, scrollHeight, clientHeight } = drawerContent;
if (scrollTop + clientHeight >= scrollHeight - 10) {
loadMoreData();
}
}
};
onMounted(() => {
const drawerContent = document.querySelector('.drawer-content');
if (drawerContent) {
drawerContent.addEventListener('scroll', handleScroll);
}
});
onBeforeUnmount(() => {
const drawerContent = document.querySelector('.drawer-content');
if (drawerContent) {
drawerContent.removeEventListener('scroll', handleScroll);
}
});
.load-more-trigger {
height: 1px;
}
.loading-button {
text-align: center;
margin-top: 10px;
}