鸿蒙NEXT 装饰器V2版下,父子组件双向同步

273 阅读1分钟

父组件向子组件传值,父组件用@Local,子组件接收外界传入数据,使用@Param装饰器。
由于子组件@Param装饰的变量不能在本地修改,所以需要用到@Event装饰器。
最新官方文档更新后,使用方式有所改变,使用方法如下

@Entry
@ComponentV2
struct TextExample {
  @Local parentCount = 0
  
 build() {
    Column({ space: 30 }) {
      Text('parent view text =' + this.parentCount.toString()).onClick(() => {
        this.parentCount++;
      }).backgroundColor(Color.Grey).padding(10)

      ChildView({
      //此处为修改后传参方式,在末尾加双叹号
        childNum: this.parentCount!!
      }).backgroundColor(Color.Grey).padding(10)
    }.width('100%')
  }
}

@ComponentV2
export struct ChildView {
  //Event修饰的变量名必须和被观察的变量名一致
  @Param childNum: number = 0;
  @Event $childNum: (val: number) => void;

  build() {
    Column() {
      Text('child view text = ' + this.childNum).onClick(() => {
        //改变Event观察的变量值
        this.$childNum(this.childNum + 1) 
      })
    }
  }
}

保留旧版本使用方式以作对比

@Entry
@ComponentV2
struct TextExample {
  @Local parentCount = 0

  build() {
    Column({ space: 30 }) {
      Text('parent view text =' + this.parentCount.toString()).onClick(() => {
        this.parentCount++;
      }).backgroundColor(Color.Grey).padding(10)

      ChildView({
        num: this.parentCount, changeIndex: (val: number) => {
          //父组件接收到子组件传回来的值后赋值给变量parentCount,
          //由于parentCount使用了装饰器@parentCount,所以会同步给子组件,达到双向同步
          this.parentCount = val;
        }
      }).backgroundColor(Color.Grey).padding(10)
    }.width('100%')
  }
}

@ComponentV2
export struct ChildView {
  @Param num: number = 0;
  @Event changeIndex: (val: number) => void;

  build() {
    Column() {
      Text('child view text = ' + this.num.toString()).onClick(() => {
        // this.num = this.num+1;  @Param装饰的变量的值不允许在本地修改
        this.changeIndex(this.num + 1)//将子组件想要改变的值传回父组件
      })
    }
  }
}