可以参考以下demo,@Watch与@Link组合使用 ,相关文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-watch-V5class PurchaseItem { static NextId: number = 0; public id: number; public price: number; constructor(price: number) { this.id = PurchaseItem.NextId++; this.price = price; } } @Component struct BasketViewer { @Link @Watch('onBasketUpdated') shopBasket: PurchaseItem[]; @State totalPurchase: number = 0; updateTotal(): number { let total = this.shopBasket.reduce((sum, i) => sum + i.price, 0); // 超过100欧元可享受折扣 if (total >= 100) { total = 0.9 * total; } return total; } // @Watch 回调 onBasketUpdated(propName: string): void { this.totalPurchase = this.updateTotal(); } build() { Column() { ForEach(this.shopBasket, (item: PurchaseItem) => { Text(`Price: ${item.price.toFixed(2)} €`) }, (item: PurchaseItem) => item.id.toString() ) Text(`Total: ${this.totalPurchase.toFixed(2)} €`) } } } @Entry @Component struct BasketModifier { @State shopBasket: PurchaseItem[] = []; build() { Column() { Button('Add to basket') .onClick(() => { this.shopBasket.push(new PurchaseItem(Math.round(100 * Math.random()))) }) BasketViewer({ shopBasket: $shopBasket }) } } }
可以参考以下demo,@Watch与@Link组合使用 ,相关文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-watch-V5