import ApprovalData from "../../models/approval/ApprovalData"; import {…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import ApprovalData from "../../models/approval/ApprovalData"; import { findMyApprovalOptions } from "../../api/Approval"; import QueryDTO from "../../models/QueryDTO"; import { ResultBody, STORAGE_AUTH_USER } from "../../utils/HttpHelper"; import Loadable from "../../utils/LoadingHelper"; import { BasicDataSource } from "@xmky_ohos/ui"; import { Type } from "@kit.ArkUI"; import util from "@ohos.util"; import { DateUtil } from "@xmky_ohos/util"; import { AuthUserInfo } from "../../common/CommonUrl";
@ObservedV2 export class ApprovalViewModel { @Trace id?: string; @Trace employeeNumber?: string; @Trace employeeId?: string; @Trace employeeName?: string; @Trace departmentName?: string; @Trace theme?: string; @Trace applicationTime?: Date; /**
updateDetail(detail: ApprovalData) { this.id = detail.id; this.employeeNumber = detail.employeeNumber; this.employeeId = detail.employeeId; this.employeeName = detail.employeeName; this.departmentName = detail.departmentName; this.theme = detail.theme; this.applicationTime = !detail.applicationTime || new util.types().isDate(detail.applicationTime) ? detail.applicationTime : DateUtil.parse(detail.applicationTime + ''); this.currentStatus = detail.currentStatus; this.remark = detail.remark; this.createTime = !detail.createTime || new util.types().isDate(detail.createTime) ? detail.createTime : DateUtil.parse(detail.createTime + ''); this.billId = detail.billId; this.billType = detail.billType; this.level = detail.level; this.delete = detail.delete; this.type = detail.type; this.startTime = !detail.startTime || new util.types().isDate(detail.startTime) ? detail.startTime : DateUtil.parse(detail.startTime + ''); this.endTime = !detail.endTime || new util.types().isDate(detail.endTime) ? detail.endTime : DateUtil.parse(detail.endTime + ''); this.processInstanceId = detail.processInstanceId; this.currentAssignee = detail.currentAssignee; this.currentAssigneeNumber = detail.currentAssigneeNumber; this.currentAssigneeName = detail.currentAssigneeName; this.myResult = detail.myResult; this.myReason = detail.myReason; this.billSealType = detail.billSealType; }
/**
@ObservedV2 export class ApprovalListViewModel extends BasicDataSource { @Type(ApprovalViewModel) @Trace approvals: ApprovalViewModel[] = [];
totalCount(): number { return this.approvals.length; }
getData(index: number): ApprovalViewModel { return this.approvals[index]; }
push(approval: ApprovalViewModel) { this.approvals.push(approval); this.notifyDataAdd(this.approvals.length - 1); } }
@ObservedV2 export default class ListViewModel extends Loadable { @Trace loading: number = 0; @Trace error?: string; @Type(ApprovalListViewModel) @Trace approvalListViewModel: ApprovalListViewModel = new ApprovalListViewModel(); @Trace scroller: Scroller; @Trace showSideBar: boolean = false; @Trace pageNum: number = 1; @Trace approvalOption?: number | null; context?: UIContext; pageInfos?: NavPathStack;
@Monitor('pageNum', 'approvalOption') async onQueryParamsChange(_monitor: IMonitor) { await this.queryApprovalList(); }
constructor(approvalOption: number | null = null, scroller: Scroller = new Scroller()) { super(); this.scroller = scroller; this.approvalOption = approvalOption; }
async queryApprovalList() { const res: ResultBody = await findMyApprovalOptions({ pageNum: this.pageNum, pageSize: 10, // stringEndTime: searchData.stringEndTime ? moment(searchData.stringEndTime).add(1, 'days').format("YYYY-MM-DD") : null, fromApp: true, myResult: this.approvalOption, } as QueryDTO); if (!res.success) { return; } const approvals = (res.data as ResultBody).data as ApprovalData[]; const oldCount = this.approvalListViewModel.approvals.length; if (1 >= this.pageNum) { this.approvalListViewModel.approvals = []; } this.approvalListViewModel.approvals.concat(approvals.map(approval => { const approvalViewModel = new ApprovalViewModel(); approvalViewModel.updateDetail(approval); return approvalViewModel; })); if (1 >= this.pageNum) { this.approvalListViewModel.notifyDataReload(); } else { for (let i = oldCount; i < this.approvalListViewModel.approvals.length; i++) { this.approvalListViewModel.notifyDataAdd(i); } } }
secondaryContentFontSizeVp(resource: Resource) { return this.context!.px2vp(this.context!.fp2px(getContext().resourceManager.getNumber(resource))) }
secondaryContentWidthVp(resource: Resource, length: number) { return this.secondaryContentFontSizeVp(resource) * length; } } 在鸿蒙中我既想支持刷新又想支持加载下一页,数据都是通过调用queryApprovalList更新,怎么设计才是优雅合理的
You're on the right track! The current ListViewModel already has many good elements for pagination (pageNum) and filtering (approvalOption), and uses Loadable for loading states. The key to supporting both refresh and load-more elegantly lies in:
Refresh component for pull-to-refresh, List's onScrollEnd for load-more).BasicDataSource is updated efficiently and correctly for both clearing and appending.Let's refine your ListViewModel and ApprovalListViewModel to achieve this.
ApprovalListViewModel for Batch OperationsYour ApprovalListViewModel currently has push for single items. For refresh (clearing and adding new) and load-more (appending multiple), it's more efficient to have methods for batch operations.
import { BasicDataSource } from "@xmky_ohos/ui";
import { Trace, ObservedV2, Type } from '@ohos.arkui.trace'; // Assuming these are from your ArkUI setup
import { ApprovalViewModel } from './ApprovalViewModel'; // Assuming this is in the same file or a sibling file
@ObservedV2
export class ApprovalListViewModel extends BasicDataSource<ApprovalViewModel> {
@Type(ApprovalViewModel)
@Trace approvals: ApprovalViewModel[] = [];
totalCount(): number {
return this.approvals.length;
}
getData(index: number): ApprovalViewModel {
return this.approvals[index];
}
/**
* Replaces all items in the list and notifies the UI for a complete reload.
* Useful for refresh operations or initial loading.
* @param newItems The new array of ApprovalViewModel to display.
*/
setItems(newItems: ApprovalViewModel[]) {
this.approvals = newItems;
this.notifyDataReload(); // Notify that the entire dataset has changed
}
/**
* Appends new items to the end of the list and notifies the UI.
* Useful for load more operations.
* @param itemsToAppend The array of ApprovalViewModel to append.
*/
appendItems(itemsToAppend: ApprovalViewModel[]) {
const startIndex = this.approvals.length;
this.approvals.push(...itemsToAppend);
// For BasicDataSource, if notifyDataAdd only takes a single index,
// you might need a loop or just call notifyDataReload for simplicity with batches.
// However, if the underlying List component is efficient with updates,
// notifyDataReload is often sufficient and simpler than precise range notifications.
this.notifyDataReload(); // Simpler and safe for batch appends
// If notifyDataAdd supported index and count:
// this.notifyDataAdd(startIndex, itemsToAppend.length);
// If notifyDataAdd only supports single item:
// for (let i = 0; i < itemsToAppend.length; i++) {
// this.notifyDataAdd(startIndex + i);
// }
}
/**
* Clears all items from the list and notifies the UI.
*/
clear() {
this.approvals = [];
this.notifyDataReload();
}
}
ListViewModel for Refresh and Load More LogicWe'll introduce isRefreshing and isLoadingMore flags to manage UI states, a hasMore flag to know if more data is available, and dedicated refresh() and loadMore() methods.
import ApprovalData from "../../models/approval/ApprovalData";
import { findMyApprovalOptions } from "../../api/Approval";
import QueryDTO from "../../models/QueryDTO";
import { ResultBody, STORAGE_AUTH_USER } from "../../utils/HttpHelper";
import Loadable from "../../utils/LoadingHelper";
import { BasicDataSource } from "@xmky_ohos/ui";
import { Type, ObservedV2, Trace, Computed, Monitor, UIContext, NavPathStack } from "@ohos.arkui.trace"; // Assuming these are from your ArkUI setup
import util from "@ohos.util";
import { DateUtil } from "@xmky_ohos/util";
import { AuthUserInfo } from "../../common/CommonUrl";
// Keep ApprovalViewModel as is, it's good.
// import ApprovalViewModel and ApprovalListViewModel (as refined above)
import { ApprovalViewModel, ApprovalListViewModel } from './ApprovalViewModel'; // Adjust path as needed
@ObservedV2
export default class ListViewModel extends Loadable {
// @Trace loading: number = 0; // Inherited from Loadable (0: idle, 1: loading, 2: error, 3: success)
@Trace error?: string;
@Type(ApprovalListViewModel)
@Trace approvalListViewModel: ApprovalListViewModel = new ApprovalListViewModel();
@Trace scroller: Scroller; // For connecting to UI Scrollable component
@Trace showSideBar: boolean = false;
@Trace pageNum: number = 1;
@Trace approvalOption?: number | null; // Filter option
// New states for refresh/load more UI feedback
@Trace isRefreshing: boolean = false; // True when pull-to-refresh is active
@Trace isLoadingMore: boolean = false; // True when loading more data at the bottom
@Trace hasMore: boolean = true; // True if there are more pages to load
context?: UIContext;
pageInfos?: NavPathStack;
// Remove the @Monitor on pageNum, as we'll manually control data fetching
// async onQueryParamsChange(_monitor: IMonitor) {
// await this.queryApprovalList();
// }
constructor(approvalOption: number | null = null, scroller: Scroller = new Scroller()) {
super();
this.scroller = scroller;
this.approvalOption = approvalOption;
// Initial data load when the ViewModel is created
this.refresh();
}
/**
* Main data fetching method.
* Handles both refreshing (first page) and loading more (subsequent pages).
* @param isRefreshing Indicates if this call is for a refresh operation.
*/
async fetchApprovalData(isRefreshing: boolean) {
if (this.loading === 1) { // Prevent concurrent fetches
console.warn("Already loading data. Ignoring new fetch request.");
return;
}
if (isRefreshing) {
this.isRefreshing = true;
this.pageNum = 1; // Reset to first page for refresh
this.hasMore = true; // Assume more data when starting a refresh
this.approvalListViewModel.clear(); // Clear existing data for a clean refresh
} else {
if (!this.hasMore) { // No more data to load, prevent unnecessary calls
console.info("No more data to load.");
return;
}
this.isLoadingMore = true;
this.pageNum++; // Increment page number for load more
}
this.loading = 1; // Set general loading state (from Loadable)
this.error = undefined; // Clear previous errors
try {
const res: ResultBody = await findMyApprovalOptions({
pageNum: this.pageNum,
pageSize: 10, // Assuming a page size of 10
fromApp: true,
myResult: this.approvalOption,
} as QueryDTO);
if (!res.success) {
this.error = res.message || "Failed to load approval list.";
this.loading = 2; // Error state
return;
}
// Important: `res.data` is likely the outer `ResultBody` wrapper.
// The actual pagination data (like `total`) might be inside the inner `data`.
// Let's assume `res.data` itself is `{ data: ApprovalData[], total: number }`
const apiResponseData = res.data as { data: ApprovalData[]; total?: number; totalCount?: number; };
const approvals = apiResponseData.data || [];
const newApprovalViewModels = approvals.map(approval => {
const approvalViewModel = new ApprovalViewModel();
approvalViewModel.updateDetail(approval);
return approvalViewModel;
});
if (isRefreshing) {
this.approvalListViewModel.setItems(newApprovalViewModels);
} else {
this.approvalListViewModel.appendItems(newApprovalViewModels);
}
// Determine if there's more data
// This usually depends on the backend response, e.g., `total` count or if the returned array is less than `pageSize`
const totalCount = apiResponseData.total ?? apiResponseData.totalCount;
if (typeof totalCount === 'number') {
this.hasMore = (this.pageNum * 10 < totalCount); // Assuming pageSize is 10
} else {
// Fallback: If no total count, assume no more data if less than page size was returned
this.hasMore = newApprovalViewModels.length === 10;
}
this.loading = 3; // Success state
} catch (e) {
console.error("Error fetching approval list:", e);
this.error = "An unexpected error occurred: " + (e instanceof Error ? e.message : String(e));
this.loading = 2; // Error state
} finally {
this.isRefreshing = false;
this.isLoadingMore = false;
}
}
/**
* Triggers a refresh (loads the first page).
* Call this for pull-to-refresh or initial load.
*/
async refresh() {
await this.fetchApprovalData(true);
}
/**
* Triggers loading of the next page.
* Call this when the user scrolls to the end of the list.
*/
async loadMore() {
if (!this.hasMore || this.isLoadingMore || this.isRefreshing) {
// Prevent loading more if no more data, already loading more, or refreshing
return;
}
await this.fetchApprovalData(false);
}
/**
* Monitored property: When approvalOption changes, trigger a refresh.
*/
@Monitor('approvalOption')
onApprovalOptionChange(_monitor: IMonitor) {
// Only trigger if it's not the initial constructor call setting.
// A simple way is to check if data is already present or if loading is not idle.
// Or, ensure this monitor is only active after initial load.
// For simplicity, let's just trigger refresh.
this.refresh();
}
// Your existing helper methods
secondaryContentFontSizeVp(resource: Resource) {
return this.context!.px2vp(this.context!.fp2px(getContext().resourceManager.getNumber(resource)))
}
secondaryContentWidthVp(resource: Resource, length: number) {
return this.secondaryContentFontSizeVp(resource) * length;
}
}
This is how you would typically connect this ViewModel to your UI components in HarmonyOS.
// MyApprovalListPage.ets
import { ListViewModel } from '../../viewmodel/Approval/ListViewModel';
import { ApprovalViewModel } from '../../viewmodel/Approval/ApprovalViewModel';
@Entry
@Component
struct MyApprovalListPage {
@State viewModel: ListViewModel = new ListViewModel(); // Pass initial filter or scroller if needed
build() {
Column() {
// Header or filter controls if any
Text('My Approvals')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.padding(10)
// Example of changing filter (ApprovalOption)
Row() {
Button('Pending')
.onClick(() => this.viewModel.approvalOption = 1) // Example: Set to "审批中"
.backgroundColor(this.viewModel.approvalOption === 1 ? Color.Blue : Color.Gray)
Button('Completed')
.onClick(() => this.viewModel.approvalOption = 4) // Example: Set to "已完成"
.backgroundColor(this.viewModel.approvalOption === 4 ? Color.Blue : Color.Gray)
Button('All')
.onClick(() => this.viewModel.approvalOption = null)
.backgroundColor(this.viewModel.approvalOption === null ? Color.Blue : Color.Gray)
}
.justifyContent(FlexAlign.SpaceAround)
.width('100%')
.padding({ bottom: 10 })
// The main list content
Refresh({ refreshing: this.viewModel.isRefreshing, onRefreshing: () => this.viewModel.refresh() }) {
List({ scroller: this.viewModel.scroller }) {
ForEach(this.viewModel.approvalListViewModel.approvals, (item: ApprovalViewModel) => {
ListItem() {
Column() {
Text(`Theme: ${item.theme ?? 'N/A'}`)
.fontSize(16)
.fontWeight(FontWeight.Medium)
Text(`Applicant: ${item.employeeName ?? 'N/A'}`)
.fontSize(14)
Text(`Status: ${item.currentStatusValue}`) // Using the Computed property
.fontSize(14)
.fontColor(item.currentStatus === 1 ? Color.Orange : Color.Green) // Example status coloring
Divider()
}
.width('100%')
.padding(10)
}
}, (item: ApprovalViewModel) => item.id) // Use a unique key for ForEach
// Loading more indicator
If.true(this.viewModel.isLoadingMore) {
ListItem() {
Text('Loading more...')
.width('100%')
.textAlign(TextAlign.Center)
.fontSize(16)
.padding(10)
}
}
// No more data indicator
If.true(!this.viewModel.hasMore && this.viewModel.approvalListViewModel.totalCount() > 0 && !this.viewModel.isLoadingMore) {
ListItem() {
Text('No more data available.')
.width('100%')
.textAlign(TextAlign.Center)
.fontSize(16)
.fontColor(Color.Gray)
.padding(10)
}
}
// Error message
If.true(this.viewModel.loading === 2) {
ListItem() {
Text(`Error: ${this.viewModel.error}`)
.width('100%')
.textAlign(TextAlign.Center)
.fontSize(16)
.fontColor(Color.Red)
.padding(10)
}
}
// Empty state for initial loading or no data
If.true(this.viewModel.loading === 1 && this.viewModel.approvalListViewModel.totalCount() === 0) {
ListItem() {
Text('Loading approval list...')
.width('100%')
.textAlign(TextAlign.Center)
.fontSize(16)
.fontColor(Color.Gray)
.padding(20)
}
}
If.true(this.viewModel.loading === 3 && this.viewModel.approvalListViewModel.totalCount() === 0) {
ListItem() {
Text('No approval data found.')
.width('100%')
.textAlign(TextAlign.Center)
.fontSize(16)
.fontColor(Color.Gray)
.padding(20)
}
}
}
.scrollBar(ScrollBar.Off) // Hide scrollbar if desired
.onScrollIndex((first, last) => {
// This callback can be used for more advanced load-more triggers
// or just use onScrollEnd for simplicity.
})
.onScrollEnd(() => {
// Trigger loadMore when scrolling to the end
this.viewModel.loadMore();
})
}
.layoutWeight(1) // Make the refresh component take available space
}
.width('100%')
.height('100%')
}
}
ApprovalListViewModel Enhancements:
setItems(newItems: ApprovalViewModel[]): Used by refresh() to completely replace the list data. It calls notifyDataReload(), which tells the UI to re-render the entire list from scratch.appendItems(itemsToAppend: ApprovalViewModel[]): Used by loadMore() to add new items to the existing list. It also calls notifyDataReload() for simplicity, ensuring the List component updates its view with the expanded approvals array.ListViewModel Core Logic (fetchApprovalData):
fetchApprovalData is the only method that makes the API call. This prevents code duplication.isRefreshing Parameter: This boolean flag determines the behavior:
true: It's a refresh. pageNum is reset to 1, hasMore is set to true (assuming there's data for the first page), and approvalListViewModel.clear() is called.false: It's a load-more. pageNum is incremented.isRefreshing, isLoadingMore, loading): These flags are crucial for providing UI feedback and preventing redundant calls.
isRefreshing: Specifically for the Refresh component's UI state.isLoadingMore: For showing a "Loading more..." indicator at the bottom of the list.loading (from Loadable): General loading state (0: idle, 1: loading, 2: error, 3: success). Useful for showing a full-screen loader or error messages.hasMore Flag: This boolean indicates if there are more pages to fetch. It's updated after each successful fetch based on the API response's total count or the number of items received. If !this.hasMore, loadMore() will stop.try...catch...finally block ensures loading states are reset and errors are displayed.Dedicated Public Methods:
refresh(): A public method called by the Refresh UI component's onRefreshing event. It simply calls fetchApprovalData(true).loadMore(): A public method called by the List component's onScrollEnd event. It calls fetchApprovalData(false) after checking hasMore and existing loading states.@Monitor('approvalOption'): This is perfect for automatically triggering a refresh() when the filter changes, ensuring the list always displays data relevant to the selected filter.
UI Integration:
Refresh Component: Wraps the List. Its refreshing property binds to viewModel.isRefreshing, and onRefreshing binds to viewModel.refresh().List Component:
scroller: Binds to viewModel.scroller for programmatic scrolling if needed.onScrollEnd: Binds to viewModel.loadMore() to trigger fetching the next page when the user scrolls to the bottom.If.true) of ListItem components based on viewModel.isLoadingMore, viewModel.hasMore, viewModel.loading, and viewModel.error provides a good user experience.This design provides a clean separation of concerns, robust state management, and an intuitive user experience for both refreshing and infinite scrolling.