鸿蒙HarmonyOS NEXT实战开发:多层嵌套类监听实现案例

介绍

本示例介绍使用@Observed装饰器和@ObjectLink装饰器来实现多层嵌套类对象属性变化的监听。

效果图预览

使用说明

  1. 加载完成后显示商品列表,点击刷新按钮可以刷新商品图片和价格。

实现思路

  1. 创建FistGoodsModel类,类对象是用@Observed修饰的类SecondGoodsItemList,SecondGoodsItemList类对象是用@Observed修饰的ThirdGoodsItem类,ThirdGoodsItem类对应的商品信息,是要被监听的对象。
/**
 * 表示商品详细数据的类型,是嵌套类的第三层
 * @class
 */
@Observed
export class ThirdGoodsItem {
  imgSrc: Resource; // 商品图片
  price: string; // 商品价格

  constructor(imgSrc: Resource, price: string) {
    this.imgSrc = imgSrc;
    this.price = price;
  }
}

/**
 * 表示商品列表的类型,是嵌套类的第二层
 * @class
 */
@Observed
export class SecondGoodsItemList {
  itemList: Array<ThirdGoodsItem>;

  constructor(imgSrc: Array<ThirdGoodsItem>) {
    this.itemList = imgSrc;
  }
}

/**
 * 表示商品模型的类型,是嵌套类的首层
 * @class
 */
export class FistGoodsModel {
  itemList: SecondGoodsItemList;

  constructor(itemList: SecondGoodsItemList) {
    this.itemList = itemList;
  }
}
  1. 自定义组件中用@ObjectLink修饰对应class实例。
@Component
export default struct GoodViewStruct {
  @Link model: FistGoodsModel;

  build() {
    Column() {
      SecondViews()
    }
  }
}

@Component
struct SecondViews {
  @ObjectLink data: SecondGoodsItemList

  build() {
    List() { ... }
  }
}

@Component
struct ThirdView {
  @ObjectLink item: ThirdGoodsItem

  build() {
    Column() { ... }
  }
}
  1. 更新第三层嵌套class ThirdGoodsItem的数据,UI刷新。
this.itemList.forEach((item, index) => {
  item.imgSrc = originItemList[index].imgSrc;
  item.price = originItemList[index].price;
}

高性能知识点

本示例介绍使用@Observed装饰器和@ObjectLink装饰器来解决需要单独监听多层嵌套类对象属性的方案。

工程结构&模块类型

VariableWatchView                               // har类型
|---model
|   |---GoodsModel.ets                          // 数据模型
|---view
|   |---ProductView.ets                         // 视图层-场景列表页面
|   |---VariableWatchView.ets                   // 视图层-场景主页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值