A brief introduction to V1 and V2 decorators in HarmonyOS development

To use the V1 decorator, you need to decorate the component with the @Component decorator, while V2 needs to use @ComponentV2

V1 Decorator

@State: Components manage their own states. Adding @State allows ordinary variables to become state variables. When variables are updated, the UI is automatically refreshed.@Prop: Commonly used for parent-child transmission, one-way data flow, parent components are passed to child components, and the transmission is irreversible.
The difference between
@Prop and @State, parent-child transmission can also use @State, but @Prop one-way data flow is more semantic and can avoid component state disorder@Link: Parent-child two-way communication @ObjectLink/@Observed/@Track: Partially refresh the UI, better performance, can be used to prevent image flickering @Provide/@Consume: Although the official said it is a two-way communication, in fact, it can only pass values ​​from @Provide to @Consume, and cannot be passed in the reverse direction

V2 Decorator

@Local is equivalent to @State

@Param: from parent to child, from parent component to child component, child component cannot modify the value of parent component, if modified, error will be reported, if you want to modify, you need to use @Once + Param

Note:

  1. Once once is used, the parent component only passes the value to the child component for the first time, and the subsequent child component data is maintained by itself

  2. @Param [non-@Once] way to pass the value, if the child component modifies the value of the parent component through callback, then this modification will not be synchronized to the child component

@Require: whether it must be passed
@ObservedV2 + @Tace: local refresh can be achieved, @Tace adds properties that need to set state variables
@Provider() / @Consumer(): This version truly realizes two-way communication, and its functions are more powerful than V1

@Provider() isScale: boolean = false
@Consumer() isScale: booean = false

Other decorators

@Event: callback function used to implement parent-child component communication

// Parent Component
getState = (state: string) => { console.log("状态:", state) }

// From father to son
TSMTest({
    getState: this.getState
})

// Subcomponents
@Event getState: (state: string) => void = (state: string) => {}

Watch

V1 version: @Watch
@Watch is used to monitor state variables. If the developer needs to pay attention to whether the value of a state variable has changed, @Watch can be used to set a callback function for the state variable.
Decorator parameter: required. Constant string, the string needs to be quoted. It is a reference to the method of (string) => void custom member function.

If other state variables are changed in the @Watch method, it will also cause state changes and @Watch execution;

During the first initialization, the @Watch decorated method will not be called, that is, the initialization is not considered to be a change in the state variable. The @Watch callback method will only be called when the state changes subsequently.

To avoid the generation of loops, it is recommended not to modify the current decorated state variable in the @Watch callback method;

The property value update function will delay the re-rendering of the component, so the callback function should only perform fast operations;

V2 version: @Monitor

@Monitor("isScale")
getShowScale() {
    if(this.isScale) {
        console.log("Size recovery")
    }
}

The @Monitor decorator has the ability to monitor deeply, and can monitor changes in specified items in nested classes, multi-dimensional arrays, and object arrays. Monitoring changes in member attributes in nested classes and object arrays requires that the class be decorated with @ObservedV2 and the attribute be decorated with @Trace.Only updates to state variables can trigger the callback function of @Monjtor
A singl
e @Monitor decorator can monitor changes in multiple attributes at the same time. When these attributes change together in an event, the callback method of @Monitor will only be triggered once.
In the inheritance class scenario, @Monitor can be defined in the parent and child components for the same attribute to monitor. When the attribute changes, the @Monitor callback defined in the parent and child components will be called.
@Monitor supports monitoring items in arrays, including multi-dimensional arrays and object arrays. @Monitor cannot monitor changes caused by API calls of built-in types (Array, Map, Date, Set). When @Monitor monitors the entire array, it can only observe the assignment of the entire array. You can determine whether the array has changes such as insertion and deletion by monitoring the length change of the array. Currently, only the “.” method is supported to express monitoring of deep attributes and array items.
If the properties monitored by @Monitor are changed multiple times in one event, the last modification will prevail.

Column() {
      Button("change count to 1000")
        .onClick(() => {
          for (let i = 1; i <= 1000; i++) {
            this.frequence.count = i;
          }
        })
      Button("change count to 0 then to 1000")
        .onClick(() => {
          for (let i = 999; i >= 0; i--) {
            this.frequence.count = i;
          }
          // The onCountChange method is not triggered in the end
          this.frequence.count = 1000; 
        })
    }

After clicking the button “change count to 1000”, the onCountChange method is triggered once and the log “count change from 0 to 1000” is output. After clicking the button “change count to 0 then to 1000”, the value of the attribute count does not change before and after the event and is 1000, so the onCountChange method is not triggered.

limit

When there are multiple monitoring methods for a property in a class, only the last defined monitoring method will take effect.
The target property monitored by @Monitor is determined at initialization and cannot be changed dynamically. It is not recommended for developers to use variables as parameters for @Monitor initialization.
Developers are advised to avoid changing the monitored property again in @Monitor, which will cause an infinite loop.

Summarize

@Watch can only monitor a single state variable and follow the state variable observation capability (one level).

@Monitor can monitor multiple state variables at the same time and follow the state variable observation capability (deep level) [requires

Takudzwa Bouy Tace Jangah

.

AppStorage

The V1 version of AppStorage can be directly decorated with @StorageProp + @StorageLink. The V2 decorator is slightly more complicated, but the benefits are more obvious. The V1 decorator shares one AppStorage, while the V2 decorator can implement multiple AppStorages.

@ObservedV2
class AppStorageKey {
    @Tace
    isScale: boolean = false
    textController: TextController = new TextController()
}

@Local appStorage: AppStorageKey = AppStorageV2.connect(AppStorageKey, () => new AppStorageKey())!

// use
this.appStorage.isScale = true

Custom component mix scenarios

V2 decorators cannot be used in V1’s custom components, otherwise compilation errors will occur.

When there is no variable transfer between components, V2’s custom components can be used in V1’s custom components, including custom components decorated with @ComponentV2 imported from a third party.

When there is variable transfer between components, V1’s variables are passed to V2’s custom components, with the following restrictions:

Variables in V1 that are not decorated with decorators (hereinafter referred to as ordinary variables): V2 can only receive them using @Param.

Variables in V1 that are decorated with decorators (hereinafter referred to as state variables): V2 can only receive them using @Param decorators, and are limited to simple data types such as boolean, number, enum, string, undefined, and null.

V1 decorators cannot be used in V2’s custom components, otherwise compilation errors will occur.

When there is no variable transfer between components, V2’s custom components can use V1’s custom components, including custom components decorated with @Component imported from a third party.

When there is variable transfer between components, the variables of V2 are passed to the custom components of V1, with the following restrictions:

Variables in V2 that are not decorated by decorators (hereinafter referred to as ordinary variables): If V1 uses decorators to decorate the received data, it can only be passed through @State, @Prop, and @Provide.
Variables in V2 that are decorated by decorators (hereinafter referred to as state variables): If V1 uses decorators to decorate the received data, built-in type data is not supported: Array, Set, Map, Date.

How to migrate from V1 to V2 decorators

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V14/arkts-v1-v2-migration-V14

0
Subscribe to my newsletter

Read articles from 白菜炖鱼只喝汤 directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

白菜炖鱼只喝汤
白菜炖鱼只喝汤