如何将界面上的状态变量传给服务层,在服务层修改状态变量对象的属性刷新页面

如何将界面上的状态变量传给服务层,在服务层修改状态变量对象的属性刷新页面。

HarmonyOS
2024-06-03 22:11:00
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
wngsheng
class Grade { 
  private _num: number; 
 
  constructor(num: number) { 
    this._num = num 
  } 
 
  get num(): number { 
    return this._num; 
  } 
 
  set num(num: number) { 
    this._num = num; 
  } 
} 
 
 
@Observed 
class Student extends Grade { 
  private _name: string; 
  private _age: number; 
  public static score: string = '100' 
 
  constructor(name: string, age: number, grade: number) { 
    super(grade); 
    this._name = name; 
    this._age = age; 
  } 
 
  get name(): string { 
    return this._name 
  } 
 
  set name(str: string) { 
    this._name = str; 
  } 
 
  get age(): number { 
    return this._age 
  } 
 
  set age(num: number) { 
    this._age = num; 
  } 
} 
 
@Observed 
class StudentList extends Array<Student> { 
  constructor(...list) { 
    super(...list) 
  } 
} 
 
class PageModel { 
  private _list: StudentList; 
 
  constructor() { 
    // 这里采用普通json对象赋值,会导致数据更新时,组件不刷新情况 
    this._list = new StudentList(new Student('张三', 10, 1), new Student('李四', 20, 2)); 
  } 
 
  public get list(): StudentList { 
    return this._list; 
  } 
 
  public set list(list: StudentList) { 
    this._list = list; 
  } 
 
  addList(data: Student) { 
    this._list.push(data) 
  } 
}
@Component 
struct StudentComp { 
  @ObjectLink student: Student; 
 
  build() { 
    Row() { 
      Text(`姓名:${this.student.name};`) 
        .fontSize(20) 
        .margin({ right: 10 }) 
        .onClick(() => { 
          this.student.name += 1; 
        }) 
      Text(`年龄:${this.student.age}`) 
        .fontSize(20) 
        .margin({ right: 10 }) 
        .onClick(() => { 
          this.student.age += 1; 
        }) 
 
      Text(`班级:${this.student.num}`) 
        .fontSize(20) 
        .margin({ right: 10 }) 
        .onClick(() => { 
          this.student.num += 1; 
        }) 
    } 
  } 
} 
 
 
@Component 
struct ListComp { 
  @ObjectLink list: StudentList; 
 
  build() { 
    Column() { 
      ForEach(this.list, (item: Student, index) => { 
        StudentComp({ student: item }) 
      }, item => JSON.stringify(item)) 
    } 
  } 
} 
 
@Entry 
@Component 
struct Index2 { 
  @State pageMode: PageModel = new PageModel(); 
 
  aboutToAppear() { 
 
 
  } 
 
  build() { 
    Column() { 
      Button('add') 
        .onClick(() => { 
          let a = this.pageMode; 
          console.log('---------a------' + JSON.stringify(a)) 
          this.pageMode.list[0].name = '王五' 
          // this.pageMode.addList(new Student('王五', 30)) 
        }) 
      ListComp({ 
        list: this.pageMode.list 
      }) 
    } 
    .height('100%') 
  } 
}
分享
微博
QQ
微信
回复
2024-06-04 21:38:39
相关问题
HarmonyOS 状态变量刷新问题
314浏览 • 1回复 待解决
状态变量和常规变量有什么区别?
361浏览 • 2回复 待解决
ArkTS中如何监听状态变量变化?
808浏览 • 1回复 待解决
关于状态变量@state必须知道
950浏览 • 1回复 待解决
怎么进度条更新时候刷新页面
4574浏览 • 1回复 待解决