<div
ref="tableWrapper"
style="height: 1000px; overflow-y: scroll"
@scroll="handleScroll"
>
//需要懒加载的数据
</div>
<script setup>
const tableWrapper = ref(null);
const tableData = ref([]);
const visibleData = ref([]);
const pageSize = 100; // 每页显示的数据数量
const total = ref(); // 总数据量
const currentPage = ref(1); // 当前页码
const scrollPosition = ref(0); // 滚动位置
const loadData = () => {
// 模拟异步请求数据
setTimeout(() => {
// 假设从后端获取到的数据为 response
const response = {
data: unitTypeList.value, // 当前页的数据
};
tableData.value.push(...response.data);
// console.log(tableData.value, "tableData.value");
updateVisibleData();
restoreScrollPosition();
}, 1000);
};
const updateVisibleData = () => {
const start = (currentPage.value - 1) * pageSize;
const end = currentPage.value * pageSize;
visibleData.value = tableData.value.slice(start, end);
};
const handleScroll = () => {
const wrapper = tableWrapper.value;
scrollPosition.value = wrapper.scrollTop;
const scrollHeight = wrapper.scrollHeight;
const scrollTop = wrapper.scrollTop;
const clientHeight = wrapper.clientHeight;
const reachedBottom = scrollTop + clientHeight >= scrollHeight;
if (reachedBottom && currentPage.value * pageSize < total.value) {
loading.value = true;
currentPage.value++;
loadData();
}
};
const restoreScrollPosition = () => {
const wrapper = tableWrapper.value;
wrapper.scrollTop = scrollPosition.value - 100;
loading.value = false;
};
</script>
element-plus中el-table懒加载通过@scroll=“handleScroll“属性滑动加载数据
最新推荐文章于 2024-07-03 11:55:23 发布