/** * EventChannel 数据类型映射接口 * 用于定义不同事件名称对应的数据类型 */ export type IEventChannelMap = Record; /** * EventChannel 监听回调函数类型 * @template T - 接收的数据类型 */ export type IEventChannelCallback = (data: T) => void; /** * useEventChannel 返回的类型安全的便捷方法对象 */ export type IEventChannelActions = { /** 类型安全的事件监听 */ on: (event: K, callback: IEventChannelCallback) => void; /** 类型安全的事件发送 */ emit: (event: K, data: T[K]) => void; /** 类型安全的事件移除 */ off: (event: K, callback?: IEventChannelCallback) => void; }; /** * 为任意 EventChannel 实例创建类型安全的 on/emit/off 方法 * 纯函数,不依赖 Vue 生命周期,可在任何上下文中使用 * * @template T - 事件数据类型映射,需继承 IEventChannelMap * @param eventChannel - 原始 EventChannel 实例 * @returns 返回包含 on/emit/off 的类型安全对象 * * @example * ```typescript * // 定义事件数据类型映射 * interface IMyEventMap { * acceptDataFromOpenerPage: { id: number; name: string }; * someOtherEvent: { message: string }; * } * * uni.navigateTo({ * url: "/pages/detail/index", * success(res) { * // 使用 createEventChannelActions 包装,获得类型安全的 emit * const channel = createEventChannelActions(res.eventChannel); * // emit 具有类型约束,事件名和数据类型都会被检查 * channel.emit("acceptDataFromOpenerPage", { id: 1, name: "测试" }); * } * }); * ``` */ export declare function createEventChannelActions(eventChannel: UniApp.EventChannel): IEventChannelActions; /** * 封装获取 EventChannel 并提供类型安全的 on/emit/off 便捷方法 * * @description * 用于页面间通信,监听上一个页面通过 EventChannel 传递的数据。 * 需要在页面的 setup 中使用,且页面由 navigateTo 打开。 * 组件卸载时会自动清理通过 on 注册的所有监听器。 * * @template T - 事件数据类型映射,默认为 IEventChannelMap * @returns 返回包含 on/emit/off 的类型安全对象,获取 EventChannel 失败时返回 undefined * * @example * ```typescript * // 定义事件数据类型映射 * interface IMyEventMap { * acceptDataFromOpenerPage: { id: number; name: string }; * someOtherEvent: { message: string }; * } * * // 使用 hook 监听事件(带类型约束) * const channel = useEventChannel(); * * // on — 类型安全,data 自动推导为 { id: number; name: string } * channel?.on("acceptDataFromOpenerPage", (data) => { * console.log("收到数据:", data.id, data.name); * }); * * // emit — 类型安全,data 必须匹配对应事件的数据类型 * channel?.emit("someOtherEvent", { message: "hello" }); * * // off — 类型安全移除监听 * const handler = (data: { id: number; name: string }) => { /* ... *\/ }; * channel?.off("acceptDataFromOpenerPage", handler); * * // 组件卸载时自动清理,无需手动 off * ``` */ export declare function useEventChannel(): IEventChannelActions | undefined;