uniapp实现上拉加载(分页效果)以及下拉刷新(重置数据效果)
1. pages.json中修改配置(微信小程序)
"pages": [{
"path": "pages/home/home",
"style": { // 无论下拉刷新还是上拉刷新,属性"enablePullDownRefresh"都要设置为 true
"navigationBarTitleText": "xx",
"enablePullDownRefresh": true, // true 代表开启下拉刷新
"onReachBottomDistance": 50 // 代表上拉触底50rpx的地方就会回调函数
}]
2. 在页面中定义请求的参数
export default {
name: 'maintenanceHome',
data() {
return {
mechanismList: [], // 列表数据
params: {
current: 1, // 页码
size: 10, // 数量
},
noData: false, // 没有更多数据了
};
}
}
3. 实现上拉刷新和下拉加载(注意 onPullDownRefresh 和 onShow、mounted等是同级的)
export default {
name: 'xx',
data() {
return {
mechanismList: [], // 机构列表数据
params: {
current: 1, // 第一页
size: 10, // 每页十个
status: '' // 当前状态
},
noData: false, // 没有更多数据了
};
},
onLoad() {
this.getMechanismList(); // 默认请求数据列表
},
// 上拉加载
onReachBottom() {
if (!this.noData) {
this.params.current++;
this.getMechanismList(); // 获取的数据列表
}
},
// 下拉刷新
onPullDownRefresh() {
that.params.current = 1;
that.getMechanismList(); // 获取的数据列表
uni.showToast({
title: '刷新成功',
icon: 'success',
duration: 2000
})
uni.stopPullDownRefresh(); // 停止刷新
},
methods: {
// 获取列表数据
async getMechanismList() {
uni.showLoading({title: '数据加载中'});
const data = await this.$http.post({
url: xx,
data: this.params
});
// console.log('获取列表数据------', data);
if (data.code == 200) {
uni.hideLoading(); // 关闭loading动画
const infoList = data.data.records;
if (infoList.length == 0 && this.params.current == 1) {
// console.log('首次加载没数据');
this.noData = false;
this.mechanismList = [];
} else if (infoList.length < 3 && this.params.current == 1) {
// console.log('首次加载有数据,但少于4条');
this.noData = true;
this.mechanismList = infoList;
} else if (infoList.length !== 0 && this.params.current == 1) {
// console.log('首次加载有数据');
this.noData = false;
this.mechanismList = infoList;
} else if (infoList.length !== 0 && this.params.current > 1) {
// console.log('上拉加载更多数据');
this.noData = false;
this.mechanismList = this.mechanismList.concat(infoList);
} else if (infoList.length == 0 && this.params.current > 1) {
// console.log('上拉加载没有更多数据了');
this.noData = true;
}
}
},
}
}