Skip to content

其他装饰器

@Watch 修饰符

@Watch 用来监听状态变量的变化,当它修饰的状态变量发生变更时,回调相应的方式,语法结构为:

bash

@State @Watch("function_name") count : number = 0;

上述语句表示:给状态变量 count 增加一个 @Watch 装饰器,通过 @Watch 注册一个回调方法 function_name , 当状态变量 count 被改变时, 触发 function_name 回调。

bash

@Entry @Component struct WatchTest {

  @State @Watch("onBasketUpdated") shopBasket: Array<number> = [7, 12, 47, 3];
  @State totalPurchase: number = 0;

  updateTotal(): number {
    let sum = 0;
    this.shopBasket.forEach((i) => {
      sum += i;
    });
    // 计算新的购物篮总价值,如果超过100RMB,则适用折扣
    this.totalPurchase = (sum < 100) ? sum : 0.9 * sum;
    return this.totalPurchase;
  }

  onBasketUpdated(propName: string): void {
    this.updateTotal();
  }

  build() {
    Column({space: 10}) {
      Text(`${this.totalPurchase}`)
        .fontSize(30)

      Button("add to basket")
        .onClick(() => {
          this.shopBasket.push(Math.round(100 * Math.random()))
        })
    }
    .width("100%")
    .height("100%")
    .padding(10)
  }
}

图片

集合 shopBasket 是一个状态变量,它被 @Watch 修饰符修饰并绑定了 onBasketUpdated() 方法回调,当点击按钮往 shopBasket 里添加数据时会触发 onBasketUpdated() 方法的调用,该方法里边执行了 totalPurchase 的数据计算,最后页面刷新。

@Watch 装饰器只能监听 @State@Prop@Link@ObjectLink@Provide@Consume@StorageProp 以及 @StorageLink 装饰的变量。

$$系统组件双向同步

类似 vue 里面的 v-model

使用规则

  • 当前$$支持基础类型变量,以及@State@Link@Prop装饰的变量。

  • 当前$$支持的组件

组件支持的参数/属性起始 API 版本
Checkboxselect10
CheckboxGroupselectAll10
DatePickerselected10
TimePickerselected10
MenuItemselected10
Panelmode10
Radiochecked10
Ratingrating10
Searchvalue10
SideBarContainershowSideBar10
Slidervalue10
Stepperindex10
Swiperindex10
Tabsindex10
TextAreatext10
TextInputtext10
TextPickerselected、value10
ToggleisOn10
AlphabetIndexerselected10
Selectselected、value10
BindSheetisShow10
BindContentCoverisShow10
Refreshrefreshing8
GridItemselected10
ListItemselected10

使用示例

ts

// xxx.ets
@Entry
@Component
struct TextInputExample {
  @State text: string = ''
  controller: TextInputController = new TextInputController()

  build() {
    Column({ space: 20 }) {
      Text(this.text)
      TextInput({ text: $$this.text, placeholder: 'input your word...', controller: this.controller })
        .placeholderColor(Color.Grey)
        .placeholderFont({ size: 14, weight: 400 })
        .caretColor(Color.Blue)
        .width(300)
    }.width('100%').height('100%').justifyContent(FlexAlign.Center)
  }
}