【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官网

目录
相关文章
|
JavaScript
使用原生js实现上拉加载,下拉刷新
使用原生js实现上拉加载,下拉刷新
157 0
uniapp上拉加载更多
uniapp上拉加载更多
199 0
|
5月前
|
JavaScript
原生js如何实现上拉加载下拉刷新?
原生js如何实现上拉加载下拉刷新?
35 0
|
JSON 小程序 API
小程序下拉刷新的实现
小程序下拉刷新的实现
SwipeRefreshLayout 下拉刷新控件(二)
SwipeRefreshLayout 下拉刷新控件(二)
SwipeRefreshLayout 下拉刷新控件(一)
SwipeRefreshLayout 下拉刷新控件(一)
|
iOS开发
iOS开发 - 让tableView不能下拉刷新,可以上拉加载
iOS开发 - 让tableView不能下拉刷新,可以上拉加载
303 0
|
JavaScript
原生js实现上滑加载,下拉刷新
这是手机端常见的一个功能,可能很多人都是用框架或者插件实现。 这里,我试着用原生js实现。 这样能更明白原理与底层实现
281 0
原生js实现上滑加载,下拉刷新
RecyclerView的下拉刷新和加载更多 动画
下拉刷新和加载更多 1、https://github.com/jianghejie/XRecyclerView 2、http://blog.csdn.net/jabony/article/details/44780187   动画 1、https://github.
1946 0