Skip to content
On this page

createEventHook

Category
Export Size
232 B
Last Changed
4 days ago

Utility for creating event hooks

Usage

Creating a function that uses createEventHook

ts
import { createEventHook } from '@vueuse/core'

export function useMyFetch(url) {
  const fetchResult = createEventHook<Response>()
  const fetchError = createEventHook<any>()

  fetch(url)
    .then(result => fetchResult.trigger(result))
    .catch(error => fetchError.trigger(error.message))

  return {
    onResult: fetchResult.on,
    onError: fetchError.on,
  }
}
import { createEventHook } from '@vueuse/core'

export function useMyFetch(url) {
  const fetchResult = createEventHook<Response>()
  const fetchError = createEventHook<any>()

  fetch(url)
    .then(result => fetchResult.trigger(result))
    .catch(error => fetchError.trigger(error.message))

  return {
    onResult: fetchResult.on,
    onError: fetchError.on,
  }
}

Using a function that uses createEventHook

html
<script setup lang="ts">
import { useMyFetch } from './my-fetch-function'

const { onResult, onError } = useMyFetch('my api url')

onResult((result) => {
  console.log(result)
})

onError((error) => {
  console.error(error)
})
</script>
<script setup lang="ts">
import { useMyFetch } from './my-fetch-function'

const { onResult, onError } = useMyFetch('my api url')

onResult((result) => {
  console.log(result)
})

onError((error) => {
  console.error(error)
})
</script>

Type Declarations

typescript
export declare type EventHookOn<T = any> = (fn: (param: T) => void) => {
  off: () => void
}
export declare type EventHookOff<T = any> = (fn: (param: T) => void) => void
export declare type EventHookTrigger<T = any> = (param: T) => void
export interface EventHook<T = any> {
  on: EventHookOn<T>
  off: EventHookOff<T>
  trigger: EventHookTrigger<T>
}
/**
 * Utility for creating event hooks
 *
 * @see https://vueuse.org/createEventHook
 */
export declare function createEventHook<T = any>(): EventHook<T>
export declare type EventHookOn<T = any> = (fn: (param: T) => void) => {
  off: () => void
}
export declare type EventHookOff<T = any> = (fn: (param: T) => void) => void
export declare type EventHookTrigger<T = any> = (param: T) => void
export interface EventHook<T = any> {
  on: EventHookOn<T>
  off: EventHookOff<T>
  trigger: EventHookTrigger<T>
}
/**
 * Utility for creating event hooks
 *
 * @see https://vueuse.org/createEventHook
 */
export declare function createEventHook<T = any>(): EventHook<T>

Source

SourceDocs

Contributors

Anthony Fu
wheat
Amirreza Zarkesh
超杰
sun0day

Changelog

v9.7.0 on 12/16/2022
fdd4d - feat(createEeventHook): auto dispose (#2518)

Released under the MIT License.