【vue】实现滚动条滚动到底部时发送请求获取数据

当后端给我们一个分页获取数据的接口时,我们前端可以通过设置分页按钮来获取到所有的数据,也可以通过判断滚动条位置,当滚动条滚动到底部时就发送请求获取下一页的数据,这样我们就可以不设置分页按钮也能获取到所有的数据。

要实现这个功能最主要的就是判断滚动条的位置:

如下图所示:

clientHeight表示可视区域的高;

scrollTop表示滚动条距离可视区域顶部的距离;

scrollHeight表示滚动内容的高度;

由上图我们可以得出滚动条到达底部的条件:

scrollHeight = scrollTop + clientHeight

代码实现:

<template>
  <div>
    <div ref="scrollBox" class="box" @scroll="toLoadMore">
      <div v-for="item in boxData" :key="item.id">{
    
    {item.name}}</div>
      <div v-loading='loading'></div>
    </div>
  </div>
</template>

<script>
import { getEnumValuePage } from "@/api/index"
export default {
  data(){
    return {
      boxData: [],
      // 当前页码
      currentPage: 1,
      // 添加loading动画 
      loading: true,
      // 是否最后一页,如果最后一页了就不再发送请求了
      lastPage: false
    }
  },
  methods:{
    getBoxData(){
      this.loading = true
      //传给后端的参数
      let params = {
          currentPage: this.currentPage
        }
        //发送请求
        if(!this.lastPage){
          getEnumValuePage(params).then(res=>{
            if(res.status === 0){
              this.boxData.push(...(res.data.list))
              this.loading = false
              if(res.data.list.length < 36){ //一页总共36条数据,小于36条时,表示是最后一页了
                this.lastPage = true
              }
            }
          })
        }
    },
    toLoadMore(){
      let scrollDom = this.$refs.scrollBox
      // console.log(scrollDom.clientHeight,'clientHeight'); //scrollDom 可视区域的高 290px
      // console.log(scrollDom.scrollHeight,'scrollHeight'); //scrollDom 里面的内容的高
      // console.log(scrollDom.scrollTop,'scrollTop'); //滚动条距离scrollDom顶部的距离
      // 由于scrollTop不太准确,所以这里加了个1
      if(scrollDom.clientHeight + scrollDom.scrollTop + 1 >= scrollDom.scrollHeight){
        this.currentPage ++ //页数加一
        this.getBoxData() //发送请求获取数据
      }
    },
  },
  mounted(){
    this.getBoxData()
  }
}
</script>

<style scoped lang='scss'>
.box{
  width: 200px;
  height: 300px;
  border: 5px solid black;
  overflow-y: auto;
  &>div{
    padding-left: 15px;
    line-height: 30px;
    background: rgba(255, 192, 203, 0.7);
  }
}
</style>

效果展示:

猜你喜欢

转载自blog.csdn.net/lq313131/article/details/128714341
今日推荐