HarmonyOS 鸿蒙Next中页面数据与弹窗进行交互
HarmonyOS 鸿蒙Next中页面数据与弹窗进行交互
如何实现,页面数据刷新,可以让弹窗产生相应的变化
3 回复
【背景知识】
- [@ObservedV2装饰器和@Trace装饰器](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-new-observedv2-and-trace)提供了对嵌套类对象属性变化直接观测的能力。
- @Local表示组件内部的状态,使得自定义组件内部的变量具有观测变化的能力。
- [@Monitor装饰器](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-new-monitor)提供了对V2状态变量变化的监听。
【解决方案】
- 使用@ObservedV2和@Trace装饰器,创建一个可以被观察的数据类ViewModel;
- 在V2界面中使用@Local装饰器观测ViewModel实例的变化;
- 当对象中数组元素发生变化时,因为[@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中,可以通过状态管理机制实现页面数据与弹窗的交互。具体实现方式如下:
- 使用@State装饰器定义响应式数据:
[@State](/user/State) message: string = '初始数据'
- 在页面布局中绑定数据到弹窗组件:
CustomDialog(this.message)
.onChange((value: string) => {
this.message = value
})
- 当页面数据更新时,使用状态管理自动触发弹窗更新:
// 数据更新会自动触发弹窗重渲染
this.message = '更新后的数据'
- 弹窗内容变化也可以通过回调函数同步到页面数据:
CustomDialog({
message: this.message,
onValueChange: (newValue: string) => {
this.message = newValue
}
})
这种方式利用了ArkUI的响应式特性,确保页面和弹窗之间的数据始终保持同步。


