uniapp下拉分页节流案例
时间: 2023-09-08 17:15:12 浏览: 41
以下是一个基于uniapp的下拉分页节流案例:
1. 在页面的data中定义一个数组,用来存储分页数据:
```
data() {
return {
listData: [],
currentPage: 1, // 当前页码
pageSize: 10, // 每页数据量
isLoading: false, // 是否正在加载数据
isFinished: false, // 是否已经加载完全部数据
}
}
```
2. 在页面的onLoad生命周期中,调用获取第一页数据的函数:
```
onLoad() {
this.getDataList()
}
```
3. 实现获取数据的函数getDataList:
```
async getDataList() {
if (this.isLoading || this.isFinished) return // 如果正在加载或已经加载完全部数据,则不再发起请求
this.isLoading = true // 设置正在加载标识
const res = await request({
url: '/api/list',
data: {
page: this.currentPage,
pageSize: this.pageSize,
},
})
this.isLoading = false // 请求完成后,取消正在加载标识
if (res.code === 0) {
this.listData = [...this.listData, ...res.data] // 将新数据合并到原数据中
if (res.data.length < this.pageSize) {
this.isFinished = true // 如果返回数据不足一页,则说明已经加载完全部数据
} else {
this.currentPage++ // 否则,页码加一,继续加载下一页
}
} else {
uni.showToast({
title: res.msg || '请求出错',
icon: 'none',
})
}
}
```
4. 在滚动到底部时触发加载更多数据:
```
onReachBottom() {
this.getDataList()
}
```
5. 实现下拉刷新,用于重新加载第一页数据:
```
onPullDownRefresh() {
this.currentPage = 1
this.isFinished = false
this.listData = []
this.getDataList()
uni.stopPullDownRefresh()
}
```
6. 为了防止频繁触发滚动事件,可以使用lodash的throttle函数来进行节流处理:
```
import _ from 'lodash'
export default {
data() {
return {
// ...
}
},
onLoad() {
this.getDataList()
this.throttledGetDataList = _.throttle(this.getDataList, 1000) // 在mounted中定义节流函数
},
methods: {
onScrollToLower() {
this.throttledGetDataList() // 使用节流函数
},
// ...
}
}
```