鸿蒙开发笔记

鸿蒙开发笔记-10-其他状态管理:@Watch装饰器,$$语法,

2025-03-09  本文已影响0人  今阳说

一、@Watch 装饰器:状态变化的实时监听者

核心功能
关键特性
@Watch('onDataUpdate')
private onDataUpdate(propName: string) {
  if (this.prevValue !== this.currentValue) {
    // 实际业务逻辑
  }
}
典型使用场景
@Observed //通过@Observed实现嵌套对象深度监听
class CartItem {
  constructor(public id: number, public price: number) {}
}

@Component
struct CheckoutPanel {
  //@Watch与@Link配合实现双向数据流
  @Link @Watch('updateTotal') cartItems: CartItem[]
  @State total: number = 0

  updateTotal() {
    this.total = this.cartItems.reduce((sum, item) => sum + item.price, 0)
    if (this.total > 1000) this.total *= 0.8 // 满减逻辑
  }

  build() {
    Column() {
      ForEach(this.cartItems, item => 
        Text(`商品${item.id}:¥${item.price}`)
      )
      Text(`实付:¥${this.total.toFixed(2)}`)
    }
  }
}
 @Entry
@Component
struct AppRoot {
  @Provide('theme') @Watch('themeChange') currentTheme: Theme = lightTheme

  themeChange() {
    Logger.log(`主题切换至${this.currentTheme.name}`)
  }
}

@Component
struct SettingsPage {
  @Consume('theme') theme: Theme

  build() {
    Toggle({ checked: this.theme.darkMode })
      .onChange(value => this.theme.darkMode = value)
  }
}
@Component struct SafeCounter {
    @State count: number = 0;
    @Watch('onChange')
    onChange() {
      setTimeout(() => this.count++, 0); // 使用中间层避免直接修改
    }
}

二、$$语法:动态模板字符串插值

基础语法

let name = "Alice";
let greeting = $$`Hello, ${name}!`;
// 输出: Hello, Alice!
// 简单插值
Text(`Hello, ${this.username}!`);
// 表达式支持
Text(`Price: $${(this.price * 0.9).toFixed(2)}`);

// 动态样式绑定
Row() {
  Text(`Status: ${
    this.status === 'success' ? '✅' : '❌'
  }`)
    .color(this.getStatusColor())
}
getFormattedPrice() {
    return this.price.toFixed(2);
}

Text(`Price: $${this.getFormattedPrice()}`)

三、@Track 装饰器:对象属性级更新优化

核心功能
运行机制
典型用例
// 跟踪类定义
class Product {
  @Track price: number = 100;
  @Track stock: number = 50;
  description: string = "Default Product";
}

// 组件使用
@Component struct ProductCard {
  @State product: Product = new Product();
  
  build() {
    Column([
      Text(`Price: $${this.product.price}`).fontSize(20),
      Text(`Stock: ${this.product.stock}`).fontSize(20),
      Button('Update Price').onClick(() => this.product.price += 10)
    ])
  }
}

四、装饰器协同模式

@Watch + @Track 组合

class DataModel {
  @Track name: string;
  @Track age: number;
}

@Component struct DataView {
  @State model: DataModel = new DataModel();
  
  @Watch('name') onChangeName() {
    console.log(`Name changed to ${this.model.name}`);
  }
  
  @Watch('age') onChangeAge() {
    console.log(`Age changed to ${this.model.age}`);
  }
}

$$语法与状态管理结合

@Component struct UserProfile {
  @State user: { name: string; avatar: string } = { name: 'Alice', avatar: 'default' };
  
  build() {
    Column([
      Text(`Welcome, ${this.user.name}!`),
      Image(this.user.avatar)
        .width(100)
        .height(100)
    ])
  }
}

五、总结与建议

六、常见问题

我是今阳,如果想要进阶和了解更多的干货,欢迎关注微信公众号 “今阳说” 接收我的最新文章

上一篇 下一篇

猜你喜欢

热点阅读