有没有分开监听同一个类中不同属性的方法?

//类的定义: 
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 
}
HarmonyOS
2024-05-30 22:52:55
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
coolhead2000
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 }) 
    } 
  } 
}
分享
微博
QQ
微信
回复
2024-05-31 21:56:10
相关问题
同一个HSP,router.pushUrlurl问题
285浏览 • 1回复 待解决
HarmonyOS 多module同时依赖同一个har
562浏览 • 1回复 待解决
如何实现一个监听网络变化方法
492浏览 • 1回复 待解决