一、定义数据
data() {return {list: [], //数据列表noMore: false, // 全部加载后底部提示total: 0, // 总条数data: {page: 1, // 页码limit: 10 // 每次请求数量},};},
二、启用下拉刷新
在页面的 .json 配置文件中,将 enablePullDownRefresh
设置为 true
三、监听下拉刷新
操作下拉刷新时,设置当前页数、总数、请求列表清零等
再次发起请求,请求完毕停止下拉刷新效果
onPullDownRefresh() {this.data.page = 1this.total = 0this.list = []this.record()uni.stopPullDownRefresh()},
四、上拉触底加载
onReachBottom() {if (this.data.page * this.data.limit >= this.total) {this.noMore = truereturn}this.data.page++ // 让页码值自增+1this.record()},
五、初次加载页面的操作
首次加载页面请求数据后,进行判断:如果数据请求完毕显示‘没有更多了’
onLoad: function(options) {this.recordList();if (this.data.page * this.data.limit >= this.total) {this.noMore = truereturn}},
六、调接口拿数据
每次请求十条数据,并添加到数据列表中
async recordList() {const res = await uni.$http.get('/api/recordList', this.data)// console.log(res.data); // 每次请求返回十条数据if (res.statusCode !== 200) return uni.$showErrorMsg("获取充值记录失败")this.list = [...this.list, ...res.data.records]this.total = res.data.total // 通过接口获取总条数},
七、全部代码
<template>
<view class="content">
<uni-row v-for="(item, index) in list" :key="item.index">
... ...(需要渲染的数据)
</uni-row>
<view class="bottom" v-if="noMore">
没有更多了
</view>
</view>
</template>
<script>
export default {
data() {
return {
list: [],
noMore: false,
data: {
page: 1,
limit: 12
},
total: 0,
};
},
onLoad: function(options) {
this.recordList();
if (this.data.page * this.data.limit >= this.total) {
this.noMore = true
return
}
},
methods: {
async recordList() {
const res = await uni.$http.get('/api/recordList', this.data)
// console.log(res.data); // 每次请求是十条数据
if (res.statusCode !== 200) return uni.$showErrorMsg("获取记录失败")
this.list = [...this.list, ...res.data.records]
this.total = res.data.total
},
onPullDownRefresh() {
this.data.page = 1
this.total = 0
this.list = []
this.record()
setTimeout(() => {
uni.stopPullDownRefresh()
}, 1000);
},
onReachBottom() {
if (this.data.page * this.data.limit >= this.total) {
this.noMore = true
return
}
this.data.page++ // 让页码值自增+1
this.record()
},
}
}
</script>