97 lines
2.5 KiB
JavaScript
97 lines
2.5 KiB
JavaScript
/**
|
||
* 数据管理 Mixin
|
||
* 提供通用的数据获取、分页加载功能
|
||
*/
|
||
export const dataManagerMixin = {
|
||
data() {
|
||
return {
|
||
// 数据数组
|
||
dataList: [],
|
||
// 加载状态
|
||
loading: false,
|
||
// 分页参数
|
||
pageNum: 1,
|
||
pageSize: 10,
|
||
hasMore: true
|
||
}
|
||
},
|
||
|
||
methods: {
|
||
/**
|
||
* 获取数据
|
||
* @param {boolean} isLoadMore 是否为加载更多
|
||
* @param {Function} apiCall API调用函数
|
||
* @param {Function} dataTransformer 数据转换函数
|
||
*/
|
||
async fetchData(isLoadMore = false, apiCall, dataTransformer) {
|
||
// 只在加载更多时设置loading状态,初始加载使用页面级别loading
|
||
if (isLoadMore) {
|
||
this.loading = true
|
||
}
|
||
|
||
try {
|
||
if (isLoadMore) {
|
||
this.pageNum++
|
||
} else {
|
||
this.pageNum = 1
|
||
}
|
||
|
||
// 调用API
|
||
const response = await apiCall({
|
||
pageNum: this.pageNum,
|
||
pageSize: this.pageSize
|
||
})
|
||
|
||
if (response.code === 200) {
|
||
// 转换数据
|
||
const newData = dataTransformer ? dataTransformer(response.rows) : response.rows || []
|
||
|
||
if (isLoadMore) {
|
||
this.dataList = [...this.dataList, ...newData]
|
||
} else {
|
||
this.dataList = newData
|
||
}
|
||
|
||
// 判断是否还有更多数据
|
||
this.hasMore = response.rows.length === this.pageSize
|
||
} else {
|
||
uni.showToast({
|
||
title: response.msg || '获取数据失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
} catch (error) {
|
||
console.error('获取数据失败:', error)
|
||
uni.showToast({
|
||
title: '网络错误',
|
||
icon: 'none'
|
||
})
|
||
} finally {
|
||
// 只在加载更多时清除loading状态
|
||
if (isLoadMore) {
|
||
this.loading = false
|
||
}
|
||
}
|
||
},
|
||
|
||
/**
|
||
* 刷新数据
|
||
* @param {Function} apiCall API调用函数
|
||
* @param {Function} dataTransformer 数据转换函数
|
||
*/
|
||
refreshData(apiCall, dataTransformer) {
|
||
this.fetchData(false, apiCall, dataTransformer)
|
||
},
|
||
|
||
/**
|
||
* 加载更多数据
|
||
* @param {Function} apiCall API调用函数
|
||
* @param {Function} dataTransformer 数据转换函数
|
||
*/
|
||
loadMoreData(apiCall, dataTransformer) {
|
||
if (this.hasMore && !this.loading) {
|
||
this.fetchData(true, apiCall, dataTransformer)
|
||
}
|
||
}
|
||
}
|
||
}
|