参考代码;import { TeacherInfoModel } from './TeacherInfoModel'; import { promptAction } from '@kit.ArkUI'; @Observed export class TeacherInfoViewModel { teacherInfoModel: TeacherInfoModel = new TeacherInfoModel(); changeId(id: string): TeacherInfoModel { this.teacherInfoModel.id = id; return this.teacherInfoModel; } //检查 checkModel(teacherInfoModel: TeacherInfoModel) { this.teacherInfoModel = teacherInfoModel; } }import { getTeacherInfoModel, TeacherInfoModel } from '../comp/TeacherInfoModel'; import { TeacherInfoViewModel } from '../comp/TeacherInfoViewModel'; import { CommComponent } from './CommComponent'; import { ComponentStatus } from './CommonEnums'; import { promptAction } from '@kit.ArkUI'; @Entry @Component struct Index { @State teacherInfoViewModel: TeacherInfoViewModel = new TeacherInfoViewModel(); @State state: ComponentStatus = ComponentStatus.LOADING aboutToAppear(): void { this.state = ComponentStatus.LOADING; //发起网络请求 this.requestNetWork(); } private requestNetWork() { getTeacherInfoModel("参数").then((res: TeacherInfoModel) => { this.teacherInfoViewModel.checkModel(res); this.state = ComponentStatus.SUCCESS; }); } build() { Row() { Column() { CommComponent({ componentStatus: this.state, data: this.teacherInfoViewModel.teacherInfoModel, builder: () => { this.successBuild() }, builderLoading: () => { this.loadingBuild() } }).onClick((e) => { this.requestNetWork(); }) } .width('100%') } .height('100%') } @Builder successBuild() { //问题1 id数据不会更新 Column() { Text(`网络数据:${this.teacherInfoViewModel?.teacherInfoModel?.id} `) .fontSize(50) .fontWeight(FontWeight.Bold) } .width('100%') .onClick(() => { //问题: 点击重新请求 后看问题1 ID不会更新 let param = this.teacherInfoViewModel.changeId("onClickID") as TeacherInfoModel //此处仅用到@State,直接修改对象从而触发UI刷新 let teacherInfoViewModelTemp: TeacherInfoViewModel = new TeacherInfoViewModel() teacherInfoViewModelTemp.teacherInfoModel = param this.teacherInfoViewModel = teacherInfoViewModelTemp promptAction.showToast({ message: `更新后的id为${JSON.stringify(param)}` }) }) } @Builder loadingBuild() { Column() { Text(`Loading... `) .fontSize(50) .fontWeight(FontWeight.Bold) } .width('100%') } }
参考代码;