5.3 多页面之间的数据传递
在鸿蒙应用开发中,多页面之间的数据传递是实现组件间通信和数据共享的关键。鸿蒙提供了多种方式来实现页面之间的数据传递,例如通过路由参数、全局状态和事件总线等。
5.3.1 路由参数传递
路由参数是最常见的数据传递方式。通过导航时附加参数,可以将数据从一个页面传递到另一个页面。
示例:传递简单参数
- 页面 A 导航到页面 B 并传递参数:
@Entry
@Component
struct PageA {
build() {
Column() {
Button("跳转到页面 B").onClick(() => {
router.push({
uri: "pages/PageB",
params: { message: "Hello, PageB!" }
});
});
}
}
}
- 页面 B 接收参数:
@Entry
@Component
struct PageB {
@State message: string = this.$route.params.message;
build() {
Text(`接收到的消息:${this.message}`);
}
}
5.3.2 使用全局状态管理
对于需要在多个页面共享的数据,可以使用全局状态管理工具(如 AppStorage 或自定义状态管理器)。
示例:使用 AppStorage
- 定义全局状态:
import { AppStorage } from "@ohos/ets";
AppStorage.SetOrCreate("sharedData", "默认值");
- 页面 A 更新全局状态:
@Entry
@Component
struct PageA {
build() {
Column() {
Button("更新全局数据").onClick(() => {
AppStorage.Set("sharedData", "新的共享数据");
});
}
}
}
- 页面 B 读取全局状态:
@Entry
@Component
struct PageB {
@Observed sharedData: string = AppStorage.Get("sharedData");
build() {
Text(`共享数据:${this.sharedData}`);
}
}
5.3.3 使用事件总线
事件总线是一种解耦的通信方式,适用于多页面间的复杂数据交互。
示例:简单的事件总线实现
- 创建事件总线:
class EventBus {
private events: Map<string, Array<Function>> = new Map();
on(event: string, listener: Function) {
if (!this.events.has(event)) {
this.events.set(event, []);
}
this.events.get(event).push(listener);
}
emit(event: string, data: any) {
if (this.events.has(event)) {
this.events.get(event).forEach(listener => listener(data));
}
}
}
export const eventBus = new EventBus();
- 页面 A 发送事件:
import { eventBus } from "./EventBus";
@Entry
@Component
struct PageA {
build() {
Column() {
Button("发送消息").onClick(() => {
eventBus.emit("messageEvent", "来自页面 A 的消息");
});
}
}
}
- 页面 B 监听事件:
import { eventBus } from "./EventBus";
@Entry
@Component
struct PageB {
@State message: string = "";
onInit() {
eventBus.on("messageEvent", (data: string) => {
this.message = data;
});
}
build() {
Text(`接收到的消息:${this.message}`);
}
}
5.3.4 小结
多页面之间的数据传递可以通过路由参数、全局状态和事件总线实现。开发者可以根据具体场景选择合适的方式,以实现高效的页面通信和数据共享。
