95 Star 364 Fork 201

HarmonyOS-Cases / Cases

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 2.94 KB
一键复制 编辑 原始数据 按行查看 历史

多层嵌套类对象监听

介绍

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

效果图预览

使用说明

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

实现思路

  1. 创建FistGoodsModel类,类对象是用@Observed修饰的类SecondGoodsItemList,SecondGoodsItemList类对象是用@Observed修饰的ThirdGoodsItem类,ThirdGoodsItem类对应的商品信息,是要被监听的对象。源码参考GoodsModel.ets
/**
 * 表示商品详细数据的类型,是嵌套类的第三层
 * @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实例。源码参考ProductView.ets
@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刷新。源码参考VariableWatchView.ets
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                   // 视图层-场景主页面

模块依赖

不涉及

参考资料

@Observed装饰器和@ObjectLink装饰器:嵌套类对象属性变化

JavaScript
1
https://gitee.com/harmonyos-cases/cases.git
git@gitee.com:harmonyos-cases/cases.git
harmonyos-cases
cases
Cases
master

搜索帮助