@Preview
@Component
export struct OvenDemePage {
@State vm: VM = new VM([])
aboutToAppear(): void {
this.vm.push()
}
build() {
NavDestination() {
Column() {
Text('click')
.fontSize(50)
.onClick(() => {
this.vm.datas[0].title = 'ovnekjskdaljfa'
this.vm.push()
})
}.height(Percent.P20)
.justifyContent(FlexAlign.Center)
List({ space: 10 }) {
ForEach(this.vm.datas, (item: Item, index: number) => {
ListItem() {
JJJ({ data: item })
}
}, (item: Item, index: number) => index + "")
}.layoutWeight(1)
}.hideTitleBar(true)
.onBackPressed(() => {
DeepalRouter.pop()
return true
})
}
}
@Preview
@Component
export struct JJJ {
@ObjectLink data: Item
build() {
Text(this.data.title).fontSize(30)
}
}
/**
*
*/
@Observed
export class VM {
datas: Item[] = []
constructor(datas: Item[]) {
this.datas = datas
}
push() {
for (let i = 0; i < 10; i++) {
this.datas.push(new Item(Math.random() + " title"))
}
}
}
/**
* item
*/
@Observed
export class Item {
title?: string
constructor(title: string) {
this.title = title
}
}
因为@Observed装饰器可以观察到嵌套对象的属性变化,其他装饰器仅能观察到第二层的变化。需要将具有观测能力的类对象绑定组件,来确保当改变这些类对象的内容时,UI能够正常的刷新(New一个继承了Array的对象而不是自定义数组)。具体参考如下链接,里面列举了几种失效场景,并提供了正确的写法。
相关文档:
https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-arkui-256-V5