HarmonyOS @State创建了一个ViewModel 对象 , ViewModel里其中有2个或以上字段 , 其中一个字段赋值之后 , 界面上关联的其他字段也跟着更新了

HarmonyOS
2024-12-27 15:09:13
413浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
aquaa

可以使用构造函数的方式改变字段的值。可参考以下demo,当改变其中一个字段的值时,另一个没有改变:

import { JSON } from '@kit.ArkTS'
export default class PlayDetailViewModel {
  colorValue: string = '#00ff00'
  heightValue: number = 200
  changeColorValue = (model: PlayDetailViewModel) => {
    model.colorValue = '#00F5FF'
    console.log('changeColorValue', JSON.stringify(model))
  }
  changeHeightValue = (model: PlayDetailViewModel) => {
    model.heightValue = 100
    console.log('changeHeightValue', JSON.stringify(model))
  }

}
@Entry
@Component
struct PlayDetailPage {
  @State vm: PlayDetailViewModel = new PlayDetailViewModel()
  onPageShow(): void {
    console.log('this.vm', JSON.stringify(this.vm))
  }
  build() {
    Stack() {
      Column() {
        Text(this.vm.colorValue).width(100).height(100).backgroundColor(this.vm.colorValue)
        Text('高度:' + this.vm.heightValue).width(100).height(this.vm.heightValue).backgroundColor(Color.Red)
        Button('点击改变颜色')
          .onClick(() => {
            let self = this.vm
            this.vm.changeColorValue(self)
          })
        Button('点击改变高度')
          .onClick(() => {
            let self = this.vm
            this.vm.changeHeightValue(self)
          })
      }
    }
    .width('100%')
    .height('100%')
    .alignContent(Alignment.Top)
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
分享
微博
QQ
微信
回复
2024-12-27 17:02:32
相关问题
如何判断一个字符是不是数字?
1400浏览 • 1回复 待解决