import { isFunction } from '@vue/shared' ; import { getCurrentInstance } from '../runtime/instance' ; import { exception } from '../warn' ; const HOOKS = new Set < string > ( ) ; private export enum HookTypes { BEFORE_MOUNT = 'beforeMount' , MOUNTED = 'mounted' , BEFORE_UPDATE = 'beforeUpdate' , UPDATED = 'updated' , BEFORE_UNMOUNT = 'beforeUnmount' , UNMOUNTED = 'unmounted' , ERROR_CAPTURED = 'errorCaptured' } param hook return export function defineHook < T extends Function > ( name ) { if ( HOOKS . has ( name ) ) { exception ( 'A lifecycle hook with that identifier already exists' , `defineHook(${ name })` ) ; } HOOKS . add ( name ) ; return ( hook ) => { if ( ! isFunction ( hook ) ) { exception ( 'Lifecycle hooks requires the parameter to be a function.' , `${ name }()` ) ; } const instance = getCurrentInstance ( ) ; if ( ! instance ) { exception ( 'Lifecycle hooks needs have a setup function in its call stack.' , `${ name }()` ) ; } instance . injectHook ( name , hook ) ; } ; } /** Registers a new hook it runs before instance is mounted */ export const onBeforeMount = defineHook ( HookTypes . BEFORE_MOUNT ) ; /** Registers a new hook it runs after instance is mounted */ export const onMount = defineHook ( HookTypes . MOUNTED ) ; /** Registers a new hook it runs before instance is updated */ export const onBeforeUpdate = defineHook ( HookTypes . BEFORE_UPDATE ) ; /** Registers a new hook it runs after instance is updated */ export const onUpdate = defineHook ( HookTypes . UPDATED ) ; /** Registers a new hook it runs before instance is unmounted */ export const onBeforeUnmount = defineHook ( HookTypes . BEFORE_UNMOUNT ) ; /** Registers a new hook it runs after instance is unmounted */ export const onUnmount = defineHook ( HookTypes . UNMOUNTED ) ; /** Registers a hook it runs when an error occurs in the component or any of it's children */ export const onErrorCaptured = defineHook ( HookTypes . ERROR_CAPTURED ) ;