借助vant实现列表分页加载和下拉刷新

直接贴上代码

<template>
  <div class="hello">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <div class="container">
        <!-- 这里可以弄一个组件或者默认样式,显示暂无数据加一张图片 -->
        <div v-if='noData'>
          暂无数据
        </div>
        <template v-else>
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="- 没有更多了 -"
            @load="onLoad"
            :offset="130"
          >
            <div v-for="item in myList" :key="item.id">
              {{item.content}}
            </div>
          </van-list>
        </template>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script>

import axios from 'axios'

export default {
  name: 'HelloWorld',
  data() {
    return {
      page: 1,
      loading: false, // 当loading为true时,转圈圈
      finished: false, // 数据是否请求结束,结束会先显示- 没有更多了 -
      myList:[],
      noData: false, // 如果没有数据,显示暂无数据
      isLoading:false // 下拉的加载图案
    }
  },
  methods: {
    getInfo () {
      axios.post('/info', {
        limit: 10, // 每页请求条数
        page: this.page // 请求的页面
      })
      .then(res => {
        // 当请求成功
        if (res.code === 0) { 
          this.loading = false
          this.myList = this.myList.concat(res.data)
          this.page++
          // 如果没有数据,显示暂无数据
          if (this.myList.length === 0 && this.page === 1) {
            this.noData = true
          }
          // 如果加载完毕,显示没有更多了
          if (res.data.length === 0) {
            this.finished = true
          }
        }
      })
      .catch(error => {
        console.log(error)
      });
    },
    // 列表加载
    onLoad () {
      setTimeout(() => {
        this.getInfo()
        this.loading = true
      }, 500)
    },
    onRefresh () {
      setTimeout(() => {
        // 重新初始化这些属性
        this.isLoading = false
        this.myList = []
        this.page = 1
        this.loading = false
        this.finished = false
        this.noData = false
        // 请求信息
        this.getInfo()
      }, 500)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
/*给个最低高度,让下面的空白区域也能下拉刷新*/
.container{
  min-height: 90vh;
}
</style>

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值