小程序中的下拉刷新

300 阅读2分钟

「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战

什么是下拉刷新

下拉刷新指的是通过手指在屏幕上的下拉滑动操作,从而重新加载页面数据的行为


如何启用下拉刷新

启用下拉刷新有俩种方式:

  • 全局开启下拉刷新(不推荐)

    app.jsonwindow 节点中, 将 enablePullDownRefresh 属性值设置为 true

    "window":{
        "backgroundTextStyle":"light",
        "navigationBarBackgroundColor": "#2b4b6b",
        "navigationBarTitleText": "北京本地生活",
        "navigationBarTextStyle":"white",
        "enablePullDownRefresh":true
    },
    
  • 局部开启下拉刷新(推荐)

    在页面 .json 配置文件中, 将 enablePullDownRefresh 属性值设置为 true

    {
        "usingComponents": {},
        "enablePullDownRefresh":true
    }
    
  • 实际开发中,可能不是所有页面都需要启用下拉刷新,为需要的页面单独开启下拉刷新效果,推荐使用第二种方式


配置下拉刷新窗口的样式

在全局或局部页面的 .json 配置文件中,通过 backgroundColor 属性和 backgroundTextStyle 属性来配置下拉刷新窗口的样式

  • backgroundColor 属性用来配置下拉刷新窗口的背景颜色,仅支持16进制的颜色值
  • backgroundTextStyle 属性用来配置下拉刷新 loading 的样式,目前仅支持 darklight

全局页面的 app.json 配置文件

"window":{
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "Weixin",
    "navigationBarTextStyle":"black",
    "enablePullDownRefresh": true,
    "backgroundColor": "#2b4b6b",
    "backgroundTextStyle":"light"
},

局部页面的 .json 配置文件

{
    "backgroundColor": "#2b4b6b",
    "backgroundTextStyle": "light"
}

监听页面的下拉刷新事件

在页面的 .js 文件中,通过 onPullDownRefresh() 函数即可监听到当前页面的下拉刷新事件

onPullDownRefresh: function () {
    console.log("触发页面的下拉刷新");
},

停止下拉刷新效果

当处理完下拉刷新后,下拉刷新的 loading 效果会一直显示,不会主动消失,所以需要手动隐藏 loading 的效果。此时,调用 wx.stopPullDownRefresh() 函数可以停止当前页面下拉刷新的效果

onPullDownRefresh: function () {
    console.log("触发页面的下拉刷新");
    //关闭下拉刷新的效果
    wx.stopPullDownRefresh({
        success: (res) => {},
    })    
},