中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
//类的定义: class PlayViewModel{ url?:strring title?:string } //调用时:(此处希望分别监听url,title) @Watch ("playVMChanged") @Stage playVM: PlayViewModel = new PlayViewModel() playVMChanged(name:string){ this.url = this.playVM.url this.title = this.playVM.title }
微信扫码分享
class GreenButtonState { width: number = 0; height: number = 0; constructor(width: number, height: number) { this.width = width; this.height = height; } } @Component struct GreenButton { @Link @Watch('onUpdated') greenButtonState: GreenButtonState; onUpdated(name: String): void { console.log('111:' + this.greenButtonState.width + ' ' + this.greenButtonState.height) this.updateWidth(); this.updateHeight() } updateWidth(): void { let width = this.greenButtonState.width; console.log('width:' + width) } updateHeight(): void { let height = this.greenButtonState.height; console.log('height:' + height) } build() { Button('Green Button') .width(this.greenButtonState.width) .height(this.greenButtonState.height) .backgroundColor('#00ff00') .onClick(() => { if (this.greenButtonState.width < 700) { // 更新class的属性,变化可以被观察到同步回父组件 this.greenButtonState.width += 20; } else { // 更新class,变化可以被观察到同步回父组件 this.greenButtonState = new GreenButtonState(50, 100); } }) } } @Component struct YellowButton { @Link yellowButtonState: number; build() { Button('Yellow Button') .width(this.yellowButtonState) .height(150.0) .backgroundColor('#ffff00') .onClick(() => { // 子组件的简单类型可以同步回父组件 this.yellowButtonState += 50.0; }) } } @Entry @Component struct ShufflingContainer { @State greenButtonState: GreenButtonState = new GreenButtonState(300, 50); @State yellowButtonProp: number = 100; build() { Column() { // 简单类型从父组件@State向子组件@Link数据同步 Button('Parent View: Set yellowButton') .onClick(() => { this.yellowButtonProp = (this.yellowButtonProp < 700) ? this.yellowButtonProp + 100 : 100; }) // class类型从父组件@State向子组件@Link数据同步 Button('Parent View: Set GreenButton') .onClick(() => { this.greenButtonState.width = (this.greenButtonState.width < 700) ? this.greenButtonState.width + 30 : 100; this.greenButtonState.height = (this.greenButtonState.height < 100) ? this.greenButtonState.height + 10 : 100; }) // class类型初始化@Link GreenButton({ greenButtonState: $greenButtonState }) // 简单类型初始化@Link YellowButton({ yellowButtonState: $yellowButtonProp }) } } }