import { pauseTracking , resetTracking } from '@vue/reactivity' ; import { currentInstance , setCurrentInstance , useInstanceScope } from './component' ; import { warn , callWithAsyncErrorHandling } from './errorHandling' ; import { LifecycleHooks , InternalInstanceState } from './types' ; export function injectHook ( type , hook , target = currentInstance , prepend = false ) { if ( target ) { const hooks = target . hooks [ type ] || ( target . hooks [ type ] = [ ] ) ; const wrappedHook = hook . __weh || ( hook . __weh = ( ... args ) => { if ( target . isUnmounted ) return ; pauseTracking ( ) ; setCurrentInstance ( target ) ; const res = callWithAsyncErrorHandling ( hook , target , type , args ) ; setCurrentInstance ( null ) ; resetTracking ( ) ; return res ; } ) ; if ( prepend ) hooks . unshift ( wrappedHook ) ; else hooks . push ( wrappedHook ) ; } else if ( __DEV__ ) { warn ( `on${ type } is called when there is no active component instance to be ` + 'associated with. ' + 'Lifecycle injection APIs can only be used during execution of setup()' ) ; } } export const createHook = < T extends Function = ( ) => any > ( lifecycle ) => ( hook , target = currentInstance ) => injectHook ( lifecycle , hook , target ) ; export const onBeforeMount = createHook ( LifecycleHooks . BEFORE_MOUNT ) ; export const onMounted = createHook ( LifecycleHooks . MOUNTED ) ; export const onBeforeUpdate = createHook ( LifecycleHooks . BEFORE_UPDATE ) ; export const onUpdated = createHook ( LifecycleHooks . UPDATED ) ; export const onBeforeUnmount = createHook ( LifecycleHooks . BEFORE_UNMOUNT ) ; export const onUnmounted = createHook ( LifecycleHooks . UNMOUNTED ) ; export const invokeLifeCycle = ( type , target = currentInstance ) => { if ( target ) { const hooks = target . hooks [ type ] || [ ] ; useInstanceScope ( target . _id , ( ) => { for ( const hook of hooks ) hook ( ) ; } ) ; } else if ( __DEV__ ) { warn ( `on${ type } is invoked without instance.` ) ; } } ;