HarmonyOS 鸿蒙Next中页面数据与弹窗进行交互

HarmonyOS 鸿蒙Next中页面数据与弹窗进行交互

如何实现,页面数据刷新,可以让弹窗产生相应的变化

3 回复

【背景知识】

【解决方案】

  1. 使用@ObservedV2@Trace装饰器,创建一个可以被观察的数据类ViewModel;
  2. 在V2界面中使用@Local装饰器观测ViewModel实例的变化;
  3. 当对象中数组元素发生变化时,因为[@Trace装饰的是数组](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-new-observedv2-and-trace#trace装饰基础类型的数组),可以直接被观察,修改数组会同步变化至弹窗刷新渲染。
import { PromptAction } from '@kit.ArkUI';

[@ObservedV2](/user/ObservedV2)
class ViewModel {
  [@Trace](/user/Trace) mRecordingDaysFlow: string[] = [] // 使用[@Trace](/user/Trace)追踪mRecordingDaysFlow的变化

  constructor(mRecordingDaysFlow: string[]) {
    this.mRecordingDaysFlow = mRecordingDaysFlow;
  }
}

@Entry
@ComponentV2
struct promptActionDemo {
  [@Local](/user/Local) mViewModel: ViewModel = new ViewModel(['19', '20', '21', '22', '23', '24', '25'])
  [@Local](/user/Local) days: string[] = this.mViewModel.mRecordingDaysFlow
  private customDialogComponentId: number = 0
  prompt: PromptAction = this.getUIContext().getPromptAction()

  // 弹窗界面
  @Builder
  customDialogComponent() {
    Column() {
      Text('弹窗').fontSize(30)
      Text(this.days.toString()).fontSize(30)
      Row({ space: 50 }) {
        Button("确认").onClick(() => this.prompt.closeCustomDialog(this.customDialogComponentId))
        Button("取消").onClick(() => this.prompt.closeCustomDialog(this.customDialogComponentId))
      }
    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
  }

  build() {
    Column() {
      ForEach(this.mViewModel.mRecordingDaysFlow, (item: string) => {
        Text('days:' + item)
      })
      Button("change string")
        .onClick(() => {
          this.prompt.openCustomDialog({
            builder: () => this.customDialogComponent()
          }).then((dialogId: number) => {
            this.customDialogComponentId = dialogId
          })
          setTimeout(() => {
            this.mViewModel.mRecordingDaysFlow.splice(5,2)
          }, 2000)
        })
    }.padding('50vp')
  }
}

更多关于HarmonyOS 鸿蒙Next中页面数据与弹窗进行交互的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,页面与弹窗的交互通过UI状态管理和事件机制实现。使用@State@Prop@Link装饰器管理页面数据,弹窗组件通过自定义组件或内置弹窗(如AlertDialog)绑定这些状态数据。当页面数据变化时,弹窗内容自动更新;反之,弹窗内操作可通过事件回调修改页面状态,实现双向同步。例如,在弹窗中输入数据会实时反馈到页面变量,确保数据一致性。

在HarmonyOS Next中,可以通过状态管理机制实现页面数据与弹窗的交互。具体实现方式如下:

  1. 使用@State装饰器定义响应式数据:
[@State](/user/State) message: string = '初始数据'
  1. 在页面布局中绑定数据到弹窗组件:
CustomDialog(this.message)
  .onChange((value: string) => {
    this.message = value
  })
  1. 当页面数据更新时,使用状态管理自动触发弹窗更新:
// 数据更新会自动触发弹窗重渲染
this.message = '更新后的数据'
  1. 弹窗内容变化也可以通过回调函数同步到页面数据:
CustomDialog({
  message: this.message,
  onValueChange: (newValue: string) => {
    this.message = newValue
  }
})

这种方式利用了ArkUI的响应式特性,确保页面和弹窗之间的数据始终保持同步。

回到顶部