📌 场景介绍
在实际开发中,我们常常需要让多个组件或页面之间进行通信,比如子组件触发父组件的函数,或跨层级通知事件。HarmonyOS 提供 @ohos.eventhub 作为一种灵活的通信机制。
🧩 Step 1:创建 EventHub 实例
// common/eventHub.ts
import EventHub from '@ohos.eventhub';
const globalEventHub = new EventHub();
export default globalEventHub;
🧩 Step 2:在页面或组件中监听事件
// pages/home/home.ets
import globalEventHub from '../../common/eventHub';
@Entry
@Component
struct HomePage {
private message: string = '';
aboutToAppear() {
globalEventHub.on('messageEvent', (data: string) => {
this.message = data;
console.info('收到消息:', data);
});
}
build() {
Column() {
Text(`当前消息: ${this.message}`).fontSize(18)
}
}
}
🧩 Step 3:在另一个页面触发事件
// pages/setting/setting.ets
import globalEventHub from '../../common/eventHub';
@Entry
@Component
struct SettingPage {
build() {
Column() {
Button

2799

被折叠的 条评论
为什么被折叠?



