38 lines
832 B
TypeScript
38 lines
832 B
TypeScript
import mitt from 'mitt'
|
||
|
||
/** 应用级事件类型定义 */
|
||
type AppEventsMap = {
|
||
/** 401 未授权 */
|
||
'app:unauthorized': void
|
||
/** 请求错误(业务错误 / HTTP 错误 / 网络错误) */
|
||
'app:request:error': {
|
||
type: 'business' | 'http' | 'network'
|
||
/** HTTP 状态码(http/business 类型时有效) */
|
||
httpStatus?: number
|
||
code?: number
|
||
message: string
|
||
}
|
||
}
|
||
|
||
/** 应用级事件常量 */
|
||
export const AppEvents = {
|
||
UNAUTHORIZED: 'app:unauthorized',
|
||
REQUEST_ERROR: 'app:request:error'
|
||
} as const
|
||
|
||
/**
|
||
* 应用级事件总线(基于 mitt)
|
||
*
|
||
* @example
|
||
* ```ts
|
||
* // 注册事件
|
||
* eventBus.on(AppEvents.UNAUTHORIZED, () => {
|
||
* router.push('/auth/login')
|
||
* })
|
||
*
|
||
* // 发布事件
|
||
* eventBus.emit(AppEvents.UNAUTHORIZED)
|
||
* ```
|
||
*/
|
||
export const eventBus = mitt<AppEventsMap>()
|