📌 场景说明

当组件层级较深或跨页面通信时,props@State 传递变得复杂,此时可以用 useEventBus 实现事件发布/订阅,做到:

  • ✅ 组件之间解耦;
  • ✅ 支持多监听者;
  • ✅ 全局通信统一管理。

🧩 Step 1:封装 useEventBus Hook

// hooks/useEventBus.ts
type Handler = (...args: any[]) => void;

class EventBus {
  private events: Map<string, Handler[]> = new Map();

  on(event: string, handler: Handler) {
    if (!this.events.has(event)) {
      this.events.set(event, []);
    }
    this.events.get(event)!.push(handler);
  }

  off(event: string, handler?: Handler) {
    if (!handler) {
      this.events.delete(event);
    } else {
      const handlers = this.events.get(event);
      if (handlers) {
        this.events.set(event, handlers.filter(h => h !== handler));
      }
    }
  }

  emit(event: string, ...args: any[]) {
    const handlers = this.events.get(event);
    if (handlers) {
      handlers.forEach(h => h(...args));
    }
  }
}

const eventBus = new EventBus();
export function useEventBus() {
  return eventBus;
}

🧩 Step 2:组件 A 中发送事件

// pages/componentA/componentA.ets
import { useEventBus } from '../../hooks/useEventBus';

@Entry
@Component
struct ComponentA {
  private bus = useEventBus();

  build() {
    Column() {
      Button("发送事件").onClick(() => {
        this.bus.emit('updateName', '鸿蒙开发者');
      })
    }
    .padding(20)
  }
}

🧩 Step 3:组件 B 中监听事件

// pages/componentB/componentB.ets
import { useEventBus } from '../../hooks/useEventBus';

@Entry
@Component
struct ComponentB {
  @State name: string = '默认名';
  private bus = useEventBus();

  aboutToAppear() {
    this.bus.on('updateName', (newName: string) => {
      this.name = newName;
    });
  }

  aboutToDisappear() {
    this.bus.off('updateName'); // 建议卸载监听,防止内存泄漏
  }

  build() {
    Column() {
      Text(`当前名称:${this.name}`).fontSize(20)
    }
    .padding(20)
  }
}

✅ 效果说明

  • 点击组件 A 的按钮,B 自动接收到事件并更新内容;
  • 两组件无引用关系,实现完全解耦通信。

⚠️ 易错点提醒

问题 说明
未手动解绑事件 页面多次进入退出会造成重复触发
多个事件名重名 建议统一事件常量或使用命名空间防冲突
不支持一次性事件 如需实现 once,需手动封装增强版逻辑

🧠 拓展建议

  • 实现 once 单次触发事件;
  • 扩展为支持事件分组、带命名空间;
  • 可与 useRequest 联动,完成数据刷新通知。
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐