通用分类分页加载器的完善2.0

This commit is contained in:
WindowBird 2025-08-26 10:57:33 +08:00
parent 482a7e174e
commit 8df43ff8d4
4 changed files with 145 additions and 145 deletions

View File

@ -41,27 +41,51 @@ export function usePagination(options = {}) {
const canLoadMore = computed(() => mode === 'loadMore' && !noMore.value && !loading.value) const canLoadMore = computed(() => mode === 'loadMore' && !noMore.value && !loading.value)
/** /**
* 获取数据列表 * 获取数据
* @param {boolean} isRefresh - 是否为刷新操作 * @param {boolean} reset - 是否重置列表
*/ */
const getList = async (isRefresh = false) => { const getList = async (reset = false) => {
if (loading.value) return if (loading.value) return
try { if (reset) {
loading.value = true list.value = []
error.value = null queryParams.value.pageNum = 1
noMore.value = false
}
// 如果是刷新,重置页码 loading.value = true
if (isRefresh) { error.value = null
queryParams.value.pageNum = 1
noMore.value = false try {
const response = await fetchData(queryParams.value)
if (!response || response.code !== 200) {
throw new Error(response?.message || '获取数据失败')
} }
const res = await fetchData(queryParams.value) const { rows = [], total = 0 } = response
// 数据转换将API返回的用户数据转换为页面需要的格式
const transformedData = rows.map(user => ({
...user,
isExpanded: false, // 默认收起
// 将orders转换为devices格式
devices: user.orders
? user.orders.map(order => ({
type: order.typeName || '未知设备',
amount: order.amount || 0,
rentDate: formatDate(order.leaseTime),
period: order.suitName || '未知周期',
expiryDate: formatDate(order.expirationTime),
}))
: [],
}))
// 处理响应数据 if (reset) {
const newData = res?.rows || [] list.value = transformedData
const total = res?.total || 0 } else {
list.value.push(...transformedData)
}
// 更新分页信息 // 更新分页信息
pagination.value = { pagination.value = {
@ -71,20 +95,13 @@ export function usePagination(options = {}) {
totalPages: Math.ceil(total / pageSize), totalPages: Math.ceil(total / pageSize),
} }
// 更新数据列表
if (isRefresh || queryParams.value.pageNum === 1) {
list.value = newData
} else {
list.value = [...list.value, ...newData]
}
// 检查是否还有更多数据 // 检查是否还有更多数据
if (mode === 'loadMore') { if (mode === 'loadMore') {
noMore.value = queryParams.value.pageNum * pageSize >= total noMore.value = queryParams.value.pageNum * pageSize >= total
console.log(`noMore状态: ${noMore.value}, 当前页: ${queryParams.value.pageNum}, 每页: ${pageSize}, 总数: ${total}`) console.log(`noMore状态: ${noMore.value}, 当前页: ${queryParams.value.pageNum}, 每页: ${pageSize}, 总数: ${total}`)
} }
console.log(`获取数据成功: 第${queryParams.value.pageNum}页,共${newData.length}`) console.log(`获取数据成功: 第${queryParams.value.pageNum}页,共${transformedData.length}`)
} catch (err) { } catch (err) {
console.error('获取数据失败:', err) console.error('获取数据失败:', err)
error.value = err error.value = err
@ -160,6 +177,17 @@ export function usePagination(options = {}) {
getList() getList()
} }
/**
* 格式化日期
* @param {string} dateString - 日期字符串
* @returns {string} 格式化后的日期
*/
const formatDate = (dateString) => {
if (!dateString) return '未知'
const date = new Date(dateString)
return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`
}
return { return {
// 状态 // 状态
list, list,

View File

@ -30,7 +30,7 @@ const { list, loading, noMore, pagination, getList, loadMore } = usePagination({
fetchData: getArticleList, fetchData: getArticleList,
defaultParams: {}, defaultParams: {},
mode: 'loadMore', mode: 'loadMore',
pageSize: 9, pageSize: 15,
}) })
const detail = item => { const detail = item => {
@ -46,11 +46,11 @@ onMounted(() => {
// //
onReachBottom(() => { onReachBottom(() => {
console.log('触发上拉加载更多,当前状态:', { console.log('触发上拉加载更多,当前状态:', {
loading: loading.value, loading: loading.value,
noMore: noMore.value, noMore: noMore.value,
listLength: list.value.length, listLength: list.value.length,
total: pagination.value.total total: pagination.value.total,
}) })
loadMore() loadMore()
}) })

View File

@ -71,8 +71,8 @@
<script setup> <script setup>
import { onMounted } from 'vue' import { onMounted } from 'vue'
import { onReachBottom } from '@dcloudio/uni-app' import { onReachBottom } from '@dcloudio/uni-app'
import { usePagination } from '@/composables/usePagination.js'
import { getMyOrder } from '@/api/order/myOrder.js' import { getMyOrder } from '@/api/order/myOrder.js'
import { usePagination } from '@/composables/usePagination.js'
import Pagination from '@/components/pagination/pagination.vue' import Pagination from '@/components/pagination/pagination.vue'
// 使 // 使

View File

@ -1,13 +1,5 @@
<template> <template>
<view class="page"> <view class="page">
<!-- 加载状态 -->
<view v-if="loading" class="loading-overlay">
<view class="loading-content">
<view class="loading-spinner"></view>
<text class="loading-text">加载中...</text>
</view>
</view>
<!-- 搜索和筛选区域 --> <!-- 搜索和筛选区域 -->
<view class="search-filter-section"> <view class="search-filter-section">
<view class="search-box"> <view class="search-box">
@ -47,7 +39,7 @@
<!-- 用户列表 --> <!-- 用户列表 -->
<view class="user-list"> <view class="user-list">
<view v-for="(user, index) in filteredUsers" :key="user.userId" class="user-card"> <view v-for="(user, index) in list" :key="user.userId" class="user-card">
<!-- 用户基本信息 --> <!-- 用户基本信息 -->
<view class="user-info"> <view class="user-info">
<view class="avatar-placeholder"></view> <view class="avatar-placeholder"></view>
@ -97,131 +89,111 @@
</view> </view>
</view> </view>
</view> </view>
<!-- 分页组件 -->
<pagination
:list="list"
:loading="loading"
:mode="'loadMore'"
:no-more="noMore"
:page-size="pagination.pageSize"
:total="pagination.total"
/>
</view> </view>
</template> </template>
<script> <script setup>
import { ref, reactive, onMounted } from 'vue'
import { onReachBottom } from '@dcloudio/uni-app'
import { commonEnum } from '@/enum/commonEnum.js' import { commonEnum } from '@/enum/commonEnum.js'
import { getUserList } from '@/api/user/user.js' import { getUserList } from '@/api/user/user.js'
import UniIcons from '../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue' import UniIcons from '../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import { usePagination } from '@/composables/usePagination.js'
import Pagination from '../../components/pagination/pagination.vue'
export default { //
components: { UniIcons }, const searchKeyword = ref('')
data() { const showFilterPanel = ref(false)
return { const filterParams = reactive({
searchKeyword: '', beginTime: '',
users: [], endTime: '',
loading: false, name: '',
showFilterPanel: false, })
filterParams: {
beginTime: '',
endTime: '',
name: '',
},
}
},
onLoad() {
this.fetchUserList()
},
computed: { // 使
filteredUsers() { const { list, loading, noMore, pagination, getList, loadMore, reset, updateParams } = usePagination(
if (!this.searchKeyword) { {
return this.users fetchData: getUserList,
} defaultParams: filterParams,
return this.users.filter(user => mode: 'loadMore',
user.nickName.toLowerCase().includes(this.searchKeyword.toLowerCase()) pageSize: 6,
) }
}, )
},
methods: {
//
async fetchUserList() {
try {
//
const params = {}
if (this.filterParams.beginTime) {
params.beginTime = this.filterParams.beginTime + ' 00:00:00'
}
if (this.filterParams.endTime) {
params.endTime = this.filterParams.endTime + ' 23:59:59'
}
if (this.filterParams.name) {
params.name = this.filterParams.name
}
const response = await getUserList(params) //
if (response.code === 200 && response.rows && Array.isArray(response.rows)) { onMounted(() => {
// API getList()
this.users = response.rows.map(user => ({ })
...user,
isExpanded: false, //
// ordersdevices
devices: user.orders
? user.orders.map(order => ({
type: order.typeName || '未知设备',
amount: order.amount || 0,
rentDate: this.formatDate(order.leaseTime),
period: order.suitName || '未知周期',
expiryDate: this.formatDate(order.expirationTime),
}))
: [],
}))
console.log('用户列表获取成功:', this.users)
}
} catch (error) {
console.error('获取用户列表失败:', error)
uni.showToast({
title: '数据加载失败',
icon: 'none',
})
} finally {
this.loading = false
}
},
// //
formatDate(dateString) { onReachBottom(() => {
if (!dateString) return '未知' console.log('触发上拉加载更多,当前状态:', {
const date = new Date(dateString) loading: loading.value,
return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}` noMore: noMore.value,
}, listLength: list.value.length,
total: pagination.value.total,
})
loadMore()
})
onSearch() { //
// computed const onSearch = () => {
}, updateParams({
name: searchKeyword,
})
}
showFilter() { // /
this.showFilterPanel = !this.showFilterPanel const showFilter = () => {
}, showFilterPanel.value = !showFilterPanel.value
}
onBeginTimeChange(e) { //
this.filterParams.beginTime = e.detail.value const onBeginTimeChange = e => {
}, filterParams.beginTime = e.detail.value + ' 00:00:00'
}
onEndTimeChange(e) { //
this.filterParams.endTime = e.detail.value const onEndTimeChange = e => {
}, filterParams.endTime = e.detail.value + ' 23:59:59'
}
resetFilter() { //
this.filterParams = { const resetFilter = () => {
beginTime: '', updateParams({
endTime: '', name: '',
name: '', beginTime: '',
} endTime: '',
this.searchKeyword = '' })
}, }
applyFilter() { //
this.filterParams.name = this.searchKeyword const applyFilter = () => {
this.showFilterPanel = false updateParams(filterParams)
this.fetchUserList() }
},
toggleExpand(index) { // /
this.users[index].isExpanded = !this.users[index].isExpanded const toggleExpand = index => {
}, if (list.value[index]) {
}, list.value[index].isExpanded = !list.value[index].isExpanded
}
}
//
const formatDate = dateString => {
if (!dateString) return '未知'
const date = new Date(dateString)
return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`
} }
</script> </script>