Elment ui 表单上滑 加载更多数据方法

 方法记录 方便以后使用

方法一:

 <template>
   <div>
    <el-table
      :data="tableData"
      height="calc(100vh - 300px)"
      ref="table"
      :show-header="false">
      <el-table-column
        prop="date"
        label="日期"
        width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址">
      </el-table-column>
    </el-table>
  </div>
</template>
<script>

export default {
 data() {
    return {
       tableData: []
    }
  },
  destroyed() {
    // 清空监听
    window.removeEventListener('scroll', this.handleScroll, true);
  },
  mounted() {
    this.$refs.table.bodyWrapper.addEventListener('scroll', this.handleScroll, true);
  },
  methods: {
    handleScroll(res) {
      // 监听滚动事件
      const height = res.target;
      const clientHeight = height.clientHeight; // 表格视窗高度 即wraper
      const scrollTop = height.scrollTop; // 表格内容已滚动的高度
      const scrollHeight = height.scrollHeight; // 表格内容撑起的高度
      if (clientHeight + scrollTop === scrollHeight) {
        if (this.isMoreLoad) {
          // 请求数据
          this.getData();
        }
      }
    },
  }
}
</script>

方法二: 推荐

当页面第一次tab页面切换时 mounted 拿不到表格dom时

调用addScrollEventListener() 添加滚动监听

离开时removeScrollEventListener() 移除监听

 data() {
    return {
        isMoreLoad: true,
        scrollEventListenerAdded: false,
    }
}, 
methods: {
    // 添加监听
    addScrollEventListener() {
      this.$nextTick(() => {
        if (!this.scrollEventListenerAdded) {
          document.querySelector('.el-table__body-wrapper').addEventListener('scroll', this.handleScroll, true);
          this.scrollEventListenerAdded = true; // 标记已添加监听器
        }
      });
    },

    // 移除滚动事件监听器的方法
    removeScrollEventListener() {
      this.$nextTick(() => {
        if (this.scrollEventListenerAdded) {
          document.querySelector
            .querySelector('.el-table__body-wrapper')
            .removeEventListener('scroll', this.handleScroll, true);
          this.scrollEventListenerAdded = false; // 标记已移除监听器
        }
      });
    },

    handleScroll(res) {
      // 监听滚动事件
      const height = res.target;
      const clientHeight = height.clientHeight; // 表格视窗高度 即wraper
      const scrollTop = height.scrollTop; // 表格内容已滚动的高度
      const scrollHeight = height.scrollHeight; // 表格内容撑起的高度
      if (clientHeight + scrollTop === scrollHeight) {
        if (this.isMoreLoad) {
          this.pageData.page++;
          this.getData();
        }
      }
    },
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值