Vue+vant组件实现下拉刷新,上拉加载

1,801 阅读1分钟

1. 引入vant组件库中的PullRefresh, List组件并注册

import Vue from 'vue';
import {PullRefresh, List } from 'vant';
Vue.use(PullRefresh);
Vue.use(List);

2.Html结构

<van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="exports">

      <van-list
        v-model="loading"
        :finished="finished"
        :immediate-check="false"//是否在初始化时立即执行滚动位置检查
        :offset="100"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <p style="font-size: 18px; padding: 10px 0px">您关注的专家</p>
        <div
          class="exportsInfo"
          v-for="(item, index) in expertList"
          :key="index"
        >
          <img :src="item.avatar" alt="" />
          <div>
            <p class="expName">{{ item.realname }}</p>
            <p class="hospital">{{ item.hospitalName }}</p>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

3.Js部分代码

data() {
    return {
      expertList: [], //列表
      loading: false,//加载
      finished: false,//加载结束
      refreshing: false,//下拉刷新
      currPage: 1,//页数
      pageSize: 10,//每页的数据个数
    };
  },
created() {
    this.getList();
  },
methods(){
// 调用接口请求数据
    getList() {
      const _self = this;
      let headers = {
        user_id: this.$store.state.userId,
      };
      let currPage = this.currPage,
        pageSize = this.pageSize;
      this.$axios
        .get(
          `SDSmart/coach/findByTransForUserList?currPage=${currPage}&pageSize=${pageSize}`,
          { headers }
        )
        .then((res) => {
          const rows = res.data.result_data.data;
          if (rows == null || rows.length === 0) {
            // 加载结束
            _self.finished = true;
            return;
          }
          if (rows.length < _self.pageSize) {
            // 最后一页不足10条的情况
            _self.finished = true;
          }
          //第一页时,数据赋值
          if (_self.currPage == 1) {
            _self.expertList = rows;
          } else {
            //数据拼接
            _self.expertList = _self.expertList.concat(rows);
          }
        })
        .finally(() => {
          _self.loading = false;
          _self.refreshing = false;
        });
    },
    //上拉加载事件
    onLoad() {
      this.currPage++;//每次加载页数加1
      this.getList(); //调用请求接口数据的方法
    },
    // 下拉刷新
    onRefresh() {
      this.currPage = 1;
      this.finished = false; // 不写这句会导致你上拉到底过后在下拉刷新将不能触发下拉加载事件
      this.getList(); // 加载数据
    },
   }

4.注意事项

:immediate-check="false"//是否在初始化时立即执行滚动位置检查;

:offset="100"//表示页面滚动条与底部距离小于offset时触发load事件。

5.后台数据返回结构

每调一次接口返回10条数据,每次触发加载事件,都会请求一次接口,直到数据加载完毕;

image.png

一共24条数据,上拉到最底部,最后一次加载4条数据,加载完毕。

image.png