vant列表下拉刷新、上拉加载|list使用方法

发布时间 2023-12-12 16:01:49作者: 朝颜浅语

Vant列表list使用方法

Vant列表list的使用方法和注意事项

下列代码为允许下拉刷新

1.使用组件

<van-pull-refresh v-model="refreshing"  @refresh="onRefresh">
    <van-list
              v-model="loading"
              :finished="finished"
              offset="20"
              finished-text="没有更多了"
              @load="onLoad"
              :immediate-check="false"
              >
        <van-cell v-for="item in list" :key="item.id" :title="item" />
    </van-list>
</van-pull-refresh>

2.加载事件的方法

onLoad() {       
    setTimeout(() => {
        if(this.refreshing){
            this.page = 1
            this.refreshing = false
        }
        // 如果为false 才能执行 否则直接忽略这次请求
        if (!this.list_lock) {
            this.list_lock = true
            // 调用接口
            this.getList()
                .then((result)=>{
                // 如果返回的数据是第一页的数据,那么先清除当前列表防止出现因多次一页接口数据重复
                if (result.data.current == 1) {
                    this.list = []
                }
                this.finished = true
            })
                .catch()
                .finally(() => {
                this.list_lock = false
            })
        }
        // 加载状态结束
        this.loading = false
    }, 1000)
},

3.下拉刷新事件

onRefresh(){
    this.list = []
    // 上方加载动画
    this.loading = true
    // 更改为未完成状态触发触底加载
    this.finished = false
    this.onLoad() //触发获取事件的方法
}

调取接口

getList() {
    Maintenance_page.getList()
        .then((res) => {
        if (res.code == '0' && this.userId) {
            // 如果是通过下拉刷新的方式刷新页面
            this.loading = false
            if (this.page == 1) {
                this.list = res.data.deviceInfos
            } else {
                this.list = [...this.list, ...res.data.deviceInfos]
            }
            this.total = res.data.total
            let sum = this.page * this.pageSize
            if (sum >= this.total) {
                this.finished = true
            } else {
                this.finished = false
            }
            this.page++
        } else {
            this.loading = false
        }
    })
        .catch((err) => {
        this.loading = false
        console.log('getList方法错误信息 :>> ', err)
    })
},

无论是下拉刷新、切换标签栏、搜索内容等涉及刷新操作的均采用覆盖式更新,且刷新后页码不进行增加,仅单纯将列表初始化,后续需要上拉加载的时候调用onLoad自动执行加载,每加载一次后针对加载内容进行判断,是否finished,然后对页码进行操作,最后设置loading状态为false解除加载状态。