HarmonyOS鸿蒙Next中@Observed解决多层对象嵌套UI更新问题【曲线救国用法】
HarmonyOS鸿蒙Next中@Observed解决多层对象嵌套UI更新问题【曲线救国用法】
class Item {
label: string
value: string
constructor(label: string) {
this.label = label
this.value = label
}
}
class Product {
list: Array<Item>
constructor(list: Array<Item>) {
this.list = list
}
}
[@Observed](/user/Observed)
class BaseObserve {
___hide: boolean //用于触发UI更新字段
// UI界面调用才有效
update(call: Function, forceUpdate?: boolean) {
call()
if (forceUpdate) {
this.___hide = !this.___hide
}
}
}
class Avr extends BaseObserve {
product: Product //嵌套对象可以不用[@Observed](/user/Observed)
constructor(product: Product) {
super()
this.product = product
}
}
@Entry
@Component
struct Index {
@Provide("avrObj") avr: Avr = new Avr(new Product([new Item("Item1"), new Item("Item2")]))
build() {
Column({ space: 20 }) {
ForEach(this.avr.product.list, (item) => {
Row() {
Button(`K:${item.label} - V:${item.value}`)
.onClick(() => {
this.avr.update(() => {
item.value = Date.now().toString()
}, true)
})
}
})
}
.height("100%")
.width("100%")
.justifyContent(FlexAlign.Center)
}
}
更多关于HarmonyOS鸿蒙Next中@Observed解决多层对象嵌套UI更新问题【曲线救国用法】的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
导入
"class-transformer": "^0.5.1" 依赖。
然后利用:plainToInstance方法。比如:
let menuListTemp = plainToInstance(BusinessManagementBeanDataMenu_info, mBean.data?.menu_info) as BusinessManagementBeanDataMenu_info[]
第一个参数传入:当前数组中对象名称,第二个参数:传输接口返回的 数组集合。最后把转换结果 as 为你的数组集合。
更多关于HarmonyOS鸿蒙Next中@Observed解决多层对象嵌套UI更新问题【曲线救国用法】的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,@Observed
注解用于标记可观察的类,当类中的属性发生变化时,UI会自动更新。对于多层对象嵌套的情况,可以通过将嵌套对象的类也用@Observed
标记,确保嵌套对象的属性变化也能触发UI更新。此外,可以通过手动调用notifyPropertyChanged
方法来通知UI更新,从而实现“曲线救国”的效果。这种方法适用于复杂的嵌套场景,确保数据变化能够及时反映到UI上。