1. 下拉刷新事件
1.1. 什么是下拉刷新
下拉刷新是移动端的专有名词,指的是通过手指在屏幕上的下拉滑动操作,从而重新加载页面数据的行为。
1.2. 启用下拉刷新
启用下拉刷新有两种方式:
- 全局开启下拉刷新
在 app.json 的 window 节点中,将 enablePullDownRefresh 设置为 true - 局部开启下拉刷新
在页面的 .json 配置文件中,将 enablePullDownRefresh 设置为 true
在实际开发中,推荐使用第 2 种方式,为需要的页面单独开启下拉刷新的效果。
1.3. 配置下拉刷新窗口的样式
在全局或页面的 .json 配置文件中,通过 backgroundColor 和 backgroundTextStyle 来配置下拉刷新窗口的样式,其中:
- backgroundColor 用来配置下拉刷新窗口的背景颜色,仅支持16 进制的颜色值
- backgroundTextStyle 用来配置下拉刷新 loading 的样式,仅支持 dark 和 light
1.4. 监听页面的下拉刷新事件
在页面的 .js 文件中,通过 onPullDownRefresh() 函数即可监听当前页面的下拉刷新事件。
在页面的 wxml 中有如下的 UI 结构,点击按钮可以让 count 值自增 +1:
<!--pages/home/home.wxml--> <text>pages/home/home.wxml</text> <view>{{ count }}</view> <button bindtap="countAdd" type="primary" >countAdd</button>
// pages/home/home.js Page({ data: { count: 0 }, // 点击按钮 count ++ countAdd() { this.setData( { count: this.data.count+1 } ) } })
在触发页面的下拉刷新事件的时候,如果要把 count 的值重置为 0
// pages/home/home.js Page({ data: { count: 0 }, // 点击按钮 count ++ countAdd() { this.setData( { count: this.data.count+1 } ) }, onPullDownRefresh() { this.setData( { count: 0 } ) } })
1.5. 停止下拉刷新的效果
当处理完下拉刷新后,下拉刷新的 loading 效果会一直显示,不会主动消失,所以需要手动隐藏下拉刷新的 loading 效果(真机上不会停止刷新,需要手动停止)。此时,调用 wx.stopPullDownRefresh() 可以停止当前页面的下拉刷新。
// pages/home/home.js Page({ data: { count: 0 }, // 点击按钮 count ++ countAdd() { this.setData( { count: this.data.count+1 } ) }, onPullDownRefresh() { this.setData( { count: 0 } ) // 停止刷新 wx.stopPullDownRefresh() } })
2. 上拉触底事件
2.1. 什么是上拉触底
上拉触底是移动端的专有名词,通过手指在屏幕上的上拉滑动操作,从而加载更多数据的行为。
2.2. 监听页面的上拉触底事件
在页面的 .js 文件中,通过 onReachBottom() 函数即可监听当前页面的上拉触底事件。
<!--pages/home/home.wxml--> <text>pages/home/home.wxml</text> <view wx:for="{{20}}" >{{ count }}</view> <button bindtap="countAdd" type="primary" >countAdd</button>
// pages/home/home.js Page({ data: { count: 0 }, // 点击按钮 count ++ countAdd() { this.setData( { count: this.data.count+1 } ) }, onPullDownRefresh() { this.setData( { count: 0 } ) wx.stopPullDownRefresh() }, onReachBottom() { console.log('触发了下拉触底事件') } })