鸿蒙元应用与卡片使用 @LocalStorageProp 进行通讯的技术分享 原创

魔眼天王
发布于 2024-12-31 11:55
浏览
1收藏


在鸿蒙系统(HarmonyOS)的开发中,@LocalStorageProp 是一个非常有用的装饰器,用于在组件之间共享状态或数据。特别是在卡片(Card)和元服务(Meta Service)之间进行通讯时,@LocalStorageProp 可以帮助我们实现数据的持久化和同步。本文将通过一个具体的案例,详细介绍如何使用 @LocalStorageProp 进行通讯。

  1. 案例背景

假设我们正在开发一个幸运号生成器应用,其中包含一个卡片组件 LotteryNumbersWidgetCard。这个卡片组件需要显示生成的幸运号码,并且这些号码需要在不同的卡片实例之间共享。为了实现这一功能,我们可以使用 @LocalStorageProp 来存储和同步幸运号码。

  1. 案例代码分析

以下是我们提供的 LotteryNumbersWidgetCard.ets 文件的内容,其中展示了如何使用 @LocalStorageProp 进行通讯。

​
import { GenerateLotteryUtil } from '../../util/GenerateLotteryUtil';
import { LogUtil } from '../../util/LogUtil';

@Entry
@Component
struct LotteryNumbersWidgetCard {
  @LocalStorageProp('lotteryType') lotteryType: string = "5+2"
  @LocalStorageProp('lotteryNumArr') lotteryNumArr: string[] = ['11 12 13 14 15 16', '21']
  @State x: number = 1
  @State y: number = 1
  /*
   * The title.
   */
  readonly TITLE: string = 'Hello World';
  /*
   * The action type.
   */
  readonly ACTION_TYPE: string = 'router';
  /*
   * The ability name.
   */
  readonly ABILITY_NAME: string = 'EntryAbility';
  /*
   * The message.
   */
  readonly MESSAGE: string = 'add detail';
  /*
   * The width percentage setting.
   */
  readonly FULL_WIDTH_PERCENT: string = '100%';
  /*
   * The height percentage setting.
   */
  readonly FULL_HEIGHT_PERCENT: string = '100%';

  aboutToAppear(): void {

  }

  aboutToDisappear(): void {
    LogUtil.i("aboutToDisappear:postCardAction")
    postCardAction(this, {
      action: "lotteryFormState", params: { lotteryType: this.lotteryType, lotteryNumArr: this.lotteryNumArr }
    })
  }

  build() {
    Row() {
      Column() {

        Text() {
          Span(this.lotteryNumArr[0]).fontSize(22).fontColor('#ff0000')
          Span('   ')
          Span(this.lotteryNumArr[1])
            .fontSize(26)
            .fontColor('#ff001aff')
        }
        .padding({
          left: 10,
          right: 10,
          bottom: 15,
        })
        .margin({ left: 10, right: 10 })
        .borderRadius(10)
        .backgroundColor(Color.White)
        .width('100%')
        .textAlign(TextAlign.Center)

        Button('生成幸运号码', { type: ButtonType.Capsule, stateEffect: true })
          .onClick(() => {
            this.x = 1.1
            this.y = 1.1
            this.lotteryNumArr = GenerateLotteryUtil.generateLottery(this.lotteryType)
          })
          .animation({
            curve: Curve.EaseOut,
            playMode: PlayMode.AlternateReverse,
            duration: 200,
            onFinish: () => {
              this.x = 1
              this.y = 1
            }
          })

      }
      .width(this.FULL_WIDTH_PERCENT)
    }
    .height(this.FULL_HEIGHT_PERCENT)
    .onClick(() => {
      postCardAction(this, {
        action: this.ACTION_TYPE,
        abilityName: this.ABILITY_NAME,
        params: {
          message: this.MESSAGE
        }
      });
    })
  }
}

​
  1. 关键点解析

3.1. 使用 @LocalStorageProp

在上述代码中,@LocalStorageProp 装饰器用于定义需要持久化的属性。这些属性会在组件实例之间共享,并且在应用重启后仍然保留其值。

@LocalStorageProp('lotteryType') lotteryType: string = "5+2"
@LocalStorageProp('lotteryNumArr') lotteryNumArr: string[] = ['11 12 13 14 15 16', '21']
  • lotteryType: 定义了幸运号码的类型,默认值为 “5+2”。
  • lotteryNumArr: 定义了生成的幸运号码数组,默认值为 [‘11 12 13 14 15 16’, ‘21’]。
    3.2. 数据更新与同步

当用户点击“生成幸运号码”按钮时,会调用 GenerateLotteryUtil.generateLottery(this.lotteryType) 方法生成新的幸运号码,并更新 lotteryNumArr 属性。

Button('生成幸运号码', { type: ButtonType.Capsule, stateEffect: true })
  .onClick(() => {
    this.x = 1.1
    this.y = 1.1
    this.lotteryNumArr = GenerateLotteryUtil.generateLottery(this.lotteryType)
  })

由于 lotteryNumArr 使用了 @LocalStorageProp 装饰器,其值会被自动持久化,并在其他卡片实例中同步更新。

3.3. 生命周期方法

在 aboutToDisappear 生命周期方法中,通过 postCardAction 方法将当前的 lotteryType 和 lotteryNumArr 发送到卡片动作中。

aboutToDisappear(): void {
  LogUtil.i("aboutToDisappear:postCardAction")
  postCardAction(this, {
    action: "lotteryFormState", params: { lotteryType: this.lotteryType, lotteryNumArr: this.lotteryNumArr }
  })
}

这一步确保了在卡片消失时,当前的状态会被正确地传递出去。

  1. 实际开发中的注意事项

在实际开发过程中,使用 @LocalStorageProp 进行通讯时需要注意以下几点:

  • 数据类型:确保 @LocalStorageProp 装饰的属性是可序列化的,例如基本数据类型、数组、对象等。
  • 性能考虑:频繁地更新 @LocalStorageProp 属性可能会影响性能,因此应避免不必要的更新。
  • 数据一致性:在多实例共享数据时,确保数据的一致性和同步性,避免数据冲突。
  1. 总结

通过使用 @LocalStorageProp 装饰器,我们可以轻松地在鸿蒙系统的卡片组件之间共享和同步数据。这不仅简化了数据管理,还提高了应用的响应速度和用户体验。希望本文的技术分享能帮助大家更好地理解和应用 @LocalStorageProp 进行通讯。

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
标签
已于2024-12-31 11:56:27修改
收藏 1
回复
举报
回复
    相关推荐