likes
comments
collection
share

vue滚动事件(滚动出现按钮/回到顶部/底部请求分页数据)

作者站长头像
站长
· 阅读数 83

最近出现了很多页面都需要滚动翻页的需求

示例图

vue滚动事件(滚动出现按钮/回到顶部/底部请求分页数据)

template

<div id="order" @scroll="scrollEvent" ref="scrollWrapper">
  滚动条中间内容略...
<div>
// 只做示例,就用按钮简单实现功能。
<el-button round icon="el-icon-top" @click="toTop('order')" v-if="showTop">顶部</el-button>

script

// 表格滚动
scrollEvent(e) {
  if (e.srcElement.scrollTop>你希望滚动到哪个数字会出现‘回到顶部’,例如300) {
    this.showTop = true;
  } else {
    this.showTop = false;
  }
  let top = e.srcElement.scrollTop; // 保存加载前的滚动条高度
  // 滑到最底部
  if (e.srcElement.scrollTop + e.srcElement.clientHeight >= e.srcElement.scrollHeight ) {
    // 非最后一页都要继续请求
    if (this.page.total > (this.page.pageNum * this.page.pageSize)) {
      let self = this;
      // 除分页以外还有其他搜索条件
      self.searchData.pageNum = self.page.pageNum+1;
      self.searchData.pageSize = self.page.pageSize;
      后端分页接口.then((res) => {
        if (后端正确返回下一页数据) {
          self.page.list.push(...res.result.list);
          self.page.pageNum = res.result.pageNum;
          self.page.total = res.result.total;
          // 滚动条定位
          this.$nextTick(() => {
            this.$refs.scrollWrapper.scrollTo(0, top);
          })
        }
      });
    }
  }
},
// 回到顶部
toTop(name) {
  let e = document.getElementById(name);
  e.scroll({top: 0, left: 0, behavior: 'smooth' }); // smooth滚动不至于太快
},