pc端 vue项目实现滚动到底部进行分页加载

vue yekong 767℃

vue数据可视化大屏项目开发中,有一个区域数据很多,需要滚动到底部后进行数据分页加载。

div部分

<div class="cBodys hideScrollBar" ref="cBodys">
    <div class="cBody" v-for="(item,index) in sjList" :key="index">
     </div>
</div>

定义参数

pageNo: 1,
isempty:false,

创建监听

当组件滚动的时候,触发监听

this.$refs.cBodys.addEventListener("scroll", this.throttle(this.handleScroll, 500), true)

滚动事件处理

当页面滚动后,监听事件会调用该事件。

// 获取滚动位置
handleScroll() {
  console.log('滚动中')
  let scrollTop = this.$refs.cBodys.scrollTop, //变量scrollTop是滚动条滚动时,距离顶部的距
      clientHeight = this.$refs.cBodys.clientHeight, //变量windowHeight是可视区的高度
      scrollHeight = this.$refs.cBodys.scrollHeight, //变量scrollHeight是滚动条的总高度
      height = 0; //根据项目实际定义
  if (scrollTop + clientHeight >= scrollHeight - height && !this.isempty) {
    console.log('加载分页')
    this.isempty = true;
    this.pageNo = parseInt(this.pageNo) + parseInt(1);//页数+1
    this.getMore(); //调用列表list接口方法
  } else {
    return false
  }
},

节流事件

防止重复请求接口

// 节流函数(防止数据一直加载)
throttle(func, wait) {
  let lastTime = null
  let timeout
  return () => {
    let context = this;
    let now = new Date();
    let arg = arguments;
    if (now - lastTime - wait > 0) {
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
      func.apply(context, arg)
      lastTime = now
    } else if (!timeout) {
      timeout = setTimeout(() => {
        func.apply(context, arg)
      }, wait)
    }
  }
},

分页加载

加载完成后,将isempty设置为false,为下次加载分页做准备。

getMore() {
  var that = this;
  getSspList({
    streetName: this.streetName,
    type: this.type,
    status: this.status,
    pageNo: this.pageNo,
    pageSize: this.pageSize
  }).then(res => {
    res.data.sjList.forEach((type) => {
      that.sjList.push(type)
    });
    that.isempty = false
    //判断每页小于后台规定条数,不加载下一页数据
    if (res.data.length <= 9) {
      that.isempty = true;
    }
  }).catch(err => {
  })
},

首次加载

进入页面后第一次加载,以及更改条件后重新查询都算第一次加载,这时候需要重置一下分页,让其变为第一页。

getList() {
  var that = this;
  this.pageNo = 1
  that.isempty = false
  getSspList({
    streetName: this.streetName,
    type: this.type,
    status: this.status,
    pageNo: this.pageNo,
    pageSize: this.pageSize
  }).then(res => {
    that.sjList = res.data.sjList
  }).catch(err => {
  })
},

销毁监听

减少资源占用,离开页面时销毁监听。

  destroyed() {
    window.removeEventListener('scroll', this.throttle(this.handleScroll, 500), true)
  },
喜欢 (2)