多个页面的页面结构完全相同,仅仅背景图和获取的列表数据不同,因此抽出一个公共组件,该组件占据整个父页面,根据父页面传入不同的参数向接口请求不同的列表数据。
现在想实现页面的下拉加载和上拉刷新功能,因为数据在子组件中请求,所以必须在子组件中实现上拉加载和下拉刷新,而onReachBottom和onPullDownRefresh又是页面内的处理函数,无法直接应用于组件中。
本篇文章借助uni.$emit()、uni.$on()和uni.$off()实现uniapp在子组件中下拉加载(onReachBottom)和上拉刷新(onPullDownRefresh)。
首先在pages.json中引入相关配置
// pages.json
{
"path": "pages/resInfo/resPage", // 页面文件路径
style": {
"navigationBarTitleText": "我是页面标题"
"enablePullDownRefresh": true, // 开启该页面下拉刷新,默认false
"onReachBottomDistance": 100 // onReachBottom事件触发时距页面底部距离,默认50,单位px
}
},
父页面:设置监听事件,onReachBottom和onPullDownRefresh与methods同级
// 父页面
onReachBottom() {
uni.$emit('onReachBottom') // 设置监听事件
},
onPullDownRefresh() {
uni.$emit('onPullDownRefresh') // 设置监听事件
}
子组件:页面挂载前开始监听,离开页面时销毁监听,在uni.$on()的回调函数中进行上拉加载和下拉刷新操作,同样与methods同级
// 子组件
beforeMount() {
uni.$on('onReachBottom', () => { // 监听上拉加载
console.log("到达底部,onReachBottom")
})
uni.$on('onPullDownRefresh', () => { // 监听下拉刷新
console.log("进行了上拉刷新,onPullDownRefresh")
})
},
destroyed() {
uni.$off('onReachBottom') // 销毁onReachBottom监听
uni.$off('onPullDownRefresh') // 销毁onPullDownRefresh
}
附上uniapp官网链接:uniapp官方文档onReachBottom介绍 | onPullDownRefresh | uni.$emit()、uni.$on()、uni.$off()