antd-vue - - - - - table实现滚动加载数据

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值