【unapp】上拉加载,下拉刷新

简介: 【unapp】上拉加载,下拉刷新

1.上拉加载

打开项目根目录中的 pages.json 配置文件,为 subPackages 分包中的 goods_list
页面配置上拉触底的距离,在对应path下添加 "onReachBottomDistance": 触发触底函数的距离

      "path": "goods_list/goods_list",
      "style": {
        "onReachBottomDistance": 150,
        "backgroundColor": "#F8F8F8"
      }

goods_list 页面中,和 methods 节点平级,声明 onReachBottom 事件处理函数,用来监听页面的上拉触底行为:

    // 触底的事件
    onReachBottom() {
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕!')

      if (this.isloading) return

      // 让页码值自增+1
      this.queryObj.pagenum++
      this.getGoodsList()
    },

2.下拉刷新

onPullDownRefresh

在 js 中定义 onPullDownRefresh 处理函数(和onLoad等生命周期函数同级),监听该页面用户下拉刷新事件。

  • 需要在 pages.json 里,找到的当前页面的pages节点,并在 style 选项中开启 enablePullDownRefresh
  • 当处理完数据刷新后,uni.stopPullDownRefresh 可以停止当前页面的下拉刷新。

再在刚才的style节点下添加如下代码,允许下拉刷新

        "enablePullDownRefresh": true,

同样的位置添加onPullDownRefresh处理函数

// 下拉刷新的事件
onPullDownRefresh() {
  // 1. 重置关键数据
  this.queryObj.pagenum = 1
  this.total = 0
  this.isloading = false
  this.goodsList = []

  // 2. 重新发起请求
  this.getGoodsList(() => uni.stopPullDownRefresh())
}

修改 getGoodsList 函数,接收 cb 回调函数并按需进行调用:

// 获取商品列表数据的方法
async getGoodsList(cb) {
  this.isloading = true
  const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
  this.isloading = false
  // 只要数据请求完毕,就立即按需调用 cb 回调函数
  cb && cb()

  if (res.meta.status !== 200) return uni.$showMsg()
  this.goodsList = [...this.goodsList, ...res.message.goods]
  this.total = res.message.total
}

对于onPullDownRefresh和onReachBottom两个函数不太理解的可以参考以下资料:

uni-app生命周期详解_linux小百的博客-
CSDN博客

onPullDownRefresh | uni-
app官网

目录
相关文章
|
索引
UniApp 组件 u-tabs 详细讲解
UniApp 组件 u-tabs 详细讲解
2820 1
|
定位技术 开发者
uni-app获取地理位置
uni-app获取地理位置
868 0
|
JavaScript
【vue】 vue2 自定义指令 实现全屏 、对话框拖拽
【vue】 vue2 自定义指令 实现全屏 、对话框拖拽
492 2
|
人工智能 小程序 前端开发
【uniapp小程序】uploadFile文件上传
【uniapp小程序】uploadFile文件上传
2009 0
|
4月前
|
人工智能 自然语言处理 测试技术
Apipost 与 Apifox 深度对比:谁是 API 开发的最佳拍档?
在 API 开发中,Apipost 与 Apifox 是两款流行的国产工具。本文通过实际项目的对比发现,Apipost 在 AI 功能方面表现突出,如 AI 自动生成文档、测试用例、脚本等,显著提升开发效率。基础功能上,Apipost 也更全面,支持离线使用、OpenAPI 格式导出、多种协议及数据库字典导入,界面简洁易用,综合性能优于 Apifox。
240 5
|
3月前
|
Ubuntu Linux Windows
如何在Ubuntu系统中安装Wine,借此来运行Windows程序
熟悉的登录画面出现,在Ubuntu系统中扫描登录微信程序。
|
小程序
uni-app开发微信小程序使用onPullDownRefresh(下拉刷新)总结
uni-app开发微信小程序使用onPullDownRefresh(下拉刷新)总结
1905 0
|
小程序
uni-app中vue3+setup实现下拉刷新、上拉加载更多效果
uni-app中vue3+setup实现下拉刷新、上拉加载更多效果
1412 2
|
JavaScript API
深入解析JS中的visibilitychange事件:监听浏览器标签间切换的利器
深入解析JS中的visibilitychange事件:监听浏览器标签间切换的利器
712 0