一.在pages.json该页面打开下拉刷新
"path": "pages/goods/goods",
"style": {
     "navigationBarTitleText":"商品列表",
     "enablePullDownRefresh":true
}
二.下拉刷新的具体实现
方法1

在onPullDownRefresh使用数据刷新,由于getGoodsList()添加了async,因此返回的是Promise,可以使用.then()执行接下来的停止刷新的操作。具体async详细解释:跳转链接
onPullDownRefresh如下:

onPullDownRefresh () {
  this.goods = []
  this.pagenum = 1
  this.flag = false
  setTimeout(() => {
  this.getGoodsList().then(() =>{
    // console.log('刷新完了')
    uni.stopPullDownRefresh()
  })
  },1000)
}

getGoodsList()如下:

async getGoodsList () {
  const res = await this.$myRequest({
    url:'/goods/search?pagenum='+this.pagenum+'&pagesize='+this.pagesize
  })
  // 获取下一页数据,依旧保留原数据:通过展开符合并
  this.goods = [...this.goods, ...res.data.message.goods]
  // 如果没有数据了
  if (this.goods.length == res.data.message.total){
    this.flag = true
  }
},
方法2

在onPullDownRefresh中的getGoodsList()参数中添加函数

onPullDownRefresh () {
  this.goods = []
  this.pagenum = 1
  this.flag = false
  setTimeout(() => {
  this.getGoodsList(() => {
    uni.stopPullDownRefresh()
  })
}

getGoodsList()修改后如下:

async getGoodsList (callBack) {
  const res = await this.$myRequest({
    url:'/goods/search?pagenum='+this.pagenum+'&pagesize='+this.pagesize
  })
  // 获取下一页数据,依旧保留原数据:通过展开符合并
  this.goods = [...this.goods, ...res.data.message.goods]
  // 如果没有数据了
  if (this.goods.length == res.data.message.total){
    this.flag = true
  }
  callBack && callBack()
},
三、两个方法对比

相较于方法2,个人更喜欢方法1些,getGoodsList()是获取数据的方法,不喜欢在里面添加控件控制的方法。不过方法2里面的callBack && callBack()学到的时候我觉得挺绝的。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐