鸿蒙ACE-V2状态分析@Type

86 阅读1分钟

@Type装饰器:标记类属性的类型

developer.huawei.com/consumer/cn…

@Type标记类属性,使得类属性序列化时不丢失类型信息,便于类的反序列化

转换前

/**
 *
 * TypeCmp.ets
 * Created by unravel on 2024/8/2
 * @abstract
 */
import { Type } from '@kit.ArkUI';
import { PersistenceV2 } from '@kit.ArkUI';

// 数据中心
@ObservedV2
class SampleChild {
  @Trace p1: number = 0;
  p2: number = 10;
}

@ObservedV2
export class Sample {
  // 对于复杂对象需要@Type修饰,确保序列化成功
  @Type(SampleChild)
  @Trace f: SampleChild = new SampleChild();
}


@ComponentV2
export struct TypeCmp {
  prop: Sample = PersistenceV2.connect(Sample, () => new Sample())!;

  build() {
    Column() {
      Text(`Page1 add 1 to prop.p1: ${this.prop.f.p1}`)
        .fontSize(30)
        .onClick(() => {
          this.prop.f.p1++;
        })
    }
  }
}

转换后

if (!("finalizeConstruction" in ViewPU.prototype)) {
    Reflect.set(ViewPU.prototype, "finalizeConstruction", () => { });
}
import { Type } from "@ohos:arkui.StateManagement";
import { PersistenceV2 } from "@ohos:arkui.StateManagement";
// 数据中心
@ObservedV2
class SampleChild {
    @Trace
    p1: number = 0;
    p2: number = 10;
}
@ObservedV2
export class Sample {
    // 对于复杂对象需要@Type修饰,确保序列化成功
    @Type(SampleChild)
    @Trace
    f: SampleChild = new SampleChild();
}
export class TypeCmp extends ViewV2 {
    constructor(parent, params, __localStorage, elmtId = -1, paramsLambda, extraInfo) {
        super(parent, elmtId, extraInfo);
        this.prop = PersistenceV2.connect(Sample, () => new Sample())!;
        this.finalizeConstruction();
    }
    prop: Sample;
    initialRender() {
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Column.create();
        }, Column);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Text.create(`Page1 add 1 to prop.p1: ${this.prop.f.p1}`);
            Text.fontSize(30);
            Text.onClick(() => {
                this.prop.f.p1++;
            });
        }, Text);
        Text.pop();
        Column.pop();
    }
    rerender() {
        this.updateDirtyElements();
    }
}

Type 装饰器

Type装饰器是从 @kit.ArkUI中导入的

import { Type } from '@kit.ArkUI';

这个装饰器接受一个可以new的类型作为参数,并返回一个属性装饰器

image.png