鸿蒙NEXT-状态管理V1和状态管理V2的差别
·
1.在V2中没有了@Link,来进行父组件和子组件的双向绑定。
所以我们需要在子组件中通过@Event,调用父组件的事件,来实现装饰回调(白话来讲就是:子组件调用@Event装饰的函数,传入参数,修改父组件中的参数)。在父组件中,传入函数给子组件,注意需要使用箭头函数来包裹我们写入事件的函数,保证我们传入的事件的this不为空。
@Event只能使用在@ComponentV2装饰的组件中使用
示例代码:
@Entry
@ComponentV2
struct Index {
@Local title: string = "待修改";
build() {
Column() {
Child({
changeFactory: () => {
this.title="已修改"
}
})
}
}
}
@ComponentV2
struct Child {
@Event changeFactory: () => void = () => {};
build() {
Column() {
Button("改变标题")
.onClick(() => {
this.changeFactory();
})
}
}
}
2.V1中的@State转变成了@Local
@State装饰器不能感知到从外部进行的初始化
名字变了,写法仍然相同,但@Local无法和@Observed装饰的类实例对象混用。其他相同:例如,装饰简单类型数组和值类型时,可以观察到数组整体或数组项的变化和值类型的变化。
3.@Watch在V2中是@Monitor
在V1中@Watch只能监听到第一层属性变化,而在V2中@Monitor,修饰,在对应的深层变量中使用@Trace,搭配使用,可以进行深层监听。
简单实现示例代码:
@Entry
@ComponentV2
struct monitorExample {
@Local apple: number = 0;
@Monitor('apple')
onFruitChange(monitor: IMonitor) {
console.log(`apple changed from ${monitor.value()?.before} to ${monitor.value()?.now}`);
}
build() {
Column(){
Text(`apple count: ${this.apple}`)
Button("add apple")
.onClick(()=> {
this.apple++;
})
}
}
}
更多推荐
所有评论(0)