[vue] Send a request to get data when the scroll bar scrolls to the bottom

When the back end gives us an interface to obtain data by paging, our front end can obtain all the data by setting the paging button, or by judging the position of the scroll bar, when the scroll bar scrolls to the bottom, send a request to obtain the next page Data, so that we can get all the data without setting the pagination button.

The most important thing to realize this function is to judge the position of the scroll bar:

As shown below:

clientHeight indicates the height of the visible area;

scrollTop indicates the distance from the scroll bar to the top of the visible area;

scrollHeight indicates the height of the scrolling content;

From the above figure, we can get the conditions for the scroll bar to reach the bottom:

scrollHeight = scrollTop + clientHeight

Code:

<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>

Show results:

Guess you like

Origin blog.csdn.net/lq313131/article/details/128714341