中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
如何将界面上的状态变量传给服务层,在服务层修改状态变量对象的属性刷新页面。
微信扫码分享
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%') } }