下拉加载更多数据

需求:当有大量数据时,页面需要滚动条下拉到底部时加载更多

当一个列表存在成千上万条,但是又没有分页组件的情况,不能一次性加载大量数据。这个时候就需要滚动条下拉到底部时,再重新加载数据

image

思路

pageSize设置为20条或更多,超出页面高度;监听滚动条下滑,需要加一个防抖,当滚动条到达底部的时候,再次请求接口,pageNo+1,将新请求的列表数据合并已请求的数据。当最后数据加载完毕,又一次到底时,判断上一次加载的数据pageSize * pageNo >= totalCount,如果大于等于,则数据所有加载完毕

实现

  1. 获取整个滚动区域div元素,对div进行滚动监听
scrollHandle () {
  this.$nextTick(() => {
    const el = document.getElementById('scrollId')
    el.addEventListener('scroll', this.debounce, true)
  })
}
  1. 加入防抖
debounce () {
  if (this.timer) {
    clearTimeout(this.timer)
  }
  this.timer = setTimeout(() => { this.getHeight() }, 500)
}
  1. 处理滚动方法
getHeight () {
   const that = this
  const clientHeight = document.getElementById('scrollId').clientHeight
  //const htmlHeight = document.getElementById('scrollId').scrollHeight
  const htmlHeight = document.getElementById('listId').offsetHeight
  const scrollTop = document.getElementById('scrollId').scrollTop
  if (clientHeight + scrollTop === htmlHeight) {
    console.log('我到底了')
    if (that.totalCount <= that.pageNo * 20) {
      that.$message.warning('数据加载完毕')
      return
    }
    that.isLoading = true
    that.pageNo++
    // 重新请求list
    that.getMatterList()
  }
   this.timer = null
}

scrollTop: 滚动出div顶部高度

offsetHeight:div的高度加padding+border

clientHeight:div可视区域高度不包括border和margin

scrollHeight: div的全部高度,包含不可视区域

posted @ 2023-05-05 14:43  嘿!那个姑娘  阅读(154)  评论(0编辑  收藏  举报