uniapp3.0列表公用hooks封装,包含上拉加载下一页,下拉刷新,接口动态化,无数据提示
hook
usePaginatedList.js
// 列表hooks
export const usePaginatedList = (fetchFunction, initialQuery) => {
const list = ref([])
const pageNo = ref(1)
const pageSize = ref(initialQuery.pageSize || 10)
const noMoreData = ref(false)
const loading = ref(false)
const status = ref('more')
status.value = 'loading'
const fetchList = (isRefresh = false) => {
uni.showLoading() // 加载
if (isRefresh) {
pageNo.value = 1
list.value = []
noMoreData.value = false
status.value = 'loading'
} else {
status.value = 'loading'
}
loading.value = true
let query = {
...initialQuery,
'pageNo': pageNo.value,
'pageSize': pageSize.value,
}
fetchFunction(query).then(res => {
uni.hideLoading()
uni.stopPullDownRefresh() // 停止下拉刷新
loading.value = false
if (res && res.code == 0) {
if (res.data.records.length < pageSize.value) {
noMoreData.value = true
status.value = 'noMore'
} else {
status.value = 'more'
}
if (isRefresh) {
list.value = res.data.records
} else {
list.value = [...list.value, ...res.data.records]
}
pageNo.value++
} else {
tip.error(res.msg)
status.value = 'more'
}
}).catch(() => {
loading.value = false
uni.hideLoading()
uni.stopPullDownRefresh() // 停止下拉刷新
tip.error('数据获取失败')
status.value = 'more'
})
}
const ReachBottom = () => {
if (!noMoreData.value && !loading.value) {
fetchList()
}
}
const onPullDown = () => {
fetchList(true)
}
return {
list,
loading,
noMoreData,
fetchList,
ReachBottom,
onPullDown,
status
}
}
页面使用
<template>
<view class="container">
<view class="padding">
<scroll-view scroll-y class="scroll-box">
<view class="cardBoxmain padding margin-bottom " v-for="(item,index) in list" :key="index">
//列表内容.......
</view>
//此处自封的空白提示,可自行替换
<empty v-if="!list.length"></empty>
<uni-load-more :status="status" v-else/>
</scroll-view>
</view>
</view>
</template>
<script setup>
import api from "@/api/car/car.js"
import {
usePaginatedList
} from '@/hooks/usePaginatedList'
onShow(() => {
fetchList()
});
// 定义获取数据的方法
const fetchFunction = (query) => {
return api.queryChargeHis(query)
}
const initialQuery = {
'pageSize': 10,
'resType': '7'//其他参数自己定义
}
const {
list,
fetchList,
ReachBottom,
onPullDown,
status
} = usePaginatedList(fetchFunction, initialQuery)
// 监听页面上拉触底事件
onReachBottom(() => {
console.log('触底啦')
ReachBottom()
})
// 监听页面下拉刷新事件
onPullDownRefresh(() => {
console.log('下拉刷新啦')
onPullDown()
})
</script>
<style scoped lang="scss">
</style>