table实现滚动加载数据
代码如下:
<template>
<a-table
ref="tableRef"
:loading="loading"
bordered
:scroll="{
y: `calc(100vh / 2)`,
scrollToFirstRowOnChange: true,
}"
:dataSource="dataSource"
:columns="columns"
:pagination="false"
>
</a-table>
</template>
<script>
import { reactive, ref, toRefs, nextTick, onMounted, onUnmounted } from "vue";
import { getTableList } from "@/api/getTableList.js";
import throttle from "lodash/throttle";
export default {
name: "rolling-to-load-data",
setup() {
// 定义key,用以获取table标签元素
const tableRef = ref(null);
// table数据
const tableConfig = reactive({
loading: false,
total: 0,
pageNum: 1,
columns: [],
dataSource: [],
});
const getList = () => {
tableConfig.loading = true;
const params = {
page: tableConfig.pageNum,
};
getTableList(params)
.then((res) => {
const { columns: _columns, dataSource, total } = res.data;
Object.assign(tableConfig, {
columns: _columns,
dataSource:
tableConfig.pageNum == 1
? dataSource
: [...tableConfig.dataSource, ...dataSource],
total,
});
})
.finally(() => {
tableConfig.loading = false;
});
};
let lastScrollTop = 0; // 记录上一次滚动的位置
// 定义滚动监听事件处理
const handleTableScroll = throttle((event) => {
const { scrollTop, scrollHeight, clientHeight } = event.target;
if (
scrollTop > lastScrollTop &&
scrollHeight - scrollTop - clientHeight < 5
) {
// 如果还有数据没加载,则继续加载
const { dataSource, total } = tableConfig;
if (dataSource.length < total) {
tableConfig.pageNum += 1;
getList();
} else {
console.log("已加载全部数据");
}
}
lastScrollTop = scrollTop <= 0 ? 0 : scrollTop; // 更新滚动位置
}, 500);
// 添加监听事件
onMounted(() => {
getList();
nextTick(() => {
const tableBody = tableRef.value.$el.querySelector(".ant-table-body");
if (tableBody) {
tableBody.addEventListener("scroll", handleTableScroll);
}
});
});
// 组件卸载时移除
onUnmounted(() => {
const tableBody = tableRef.value?.$el?.querySelector(".ant-table-body");
if (tableBody) {
tableBody.removeEventListener("scroll", handleTableScroll);
}
});
return {
tableRef,
...toRefs(tableConfig),
getList,
};
},
};
</script>