vue3-yuanma/packages/runtime-core/src/apiLifecycle.ts

100 lines
2.6 KiB
TypeScript
Raw Normal View History

import {
ComponentInstance,
LifecycleHooks,
currentInstance,
setCurrentInstance
} from './component'
import { callWithAsyncErrorHandling, ErrorTypeStrings } from './errorHandling'
import { warn } from './warning'
import { capitalize } from '@vue/shared'
2019-05-28 19:36:15 +08:00
function injectHook(
type: LifecycleHooks,
2019-08-29 00:13:36 +08:00
hook: Function,
target: ComponentInstance | null = currentInstance
2019-05-28 19:36:15 +08:00
) {
if (target) {
;(target[type] || (target[type] = [])).push((...args: any[]) => {
// Set currentInstance during hook invocation.
// This assumes the hook does not synchronously trigger other hooks, which
// can only be false when the user does something really funky.
setCurrentInstance(target)
const res = callWithAsyncErrorHandling(hook, target, type, args)
setCurrentInstance(null)
return res
})
} else if (__DEV__) {
const apiName = `on${capitalize(
ErrorTypeStrings[name].replace(/ hook$/, '')
)}`
warn(
`${apiName} is called when there is no active component instance to be ` +
`associated with. ` +
`Lifecycle injection APIs can only be used during execution of setup().`
)
2019-05-28 19:36:15 +08:00
}
}
export function onBeforeMount(
hook: Function,
target: ComponentInstance | null = currentInstance
) {
injectHook(LifecycleHooks.BEFORE_MOUNT, hook, target)
2019-05-28 19:36:15 +08:00
}
export function onMounted(
hook: Function,
target: ComponentInstance | null = currentInstance
) {
injectHook(LifecycleHooks.MOUNTED, hook, target)
2019-05-28 19:36:15 +08:00
}
export function onBeforeUpdate(
hook: Function,
target: ComponentInstance | null = currentInstance
) {
injectHook(LifecycleHooks.BEFORE_UPDATE, hook, target)
2019-05-28 19:36:15 +08:00
}
export function onUpdated(
hook: Function,
target: ComponentInstance | null = currentInstance
) {
injectHook(LifecycleHooks.UPDATED, hook, target)
2019-05-28 19:36:15 +08:00
}
export function onBeforeUnmount(
hook: Function,
target: ComponentInstance | null = currentInstance
) {
injectHook(LifecycleHooks.BEFORE_UNMOUNT, hook, target)
2019-05-28 19:36:15 +08:00
}
export function onUnmounted(
hook: Function,
target: ComponentInstance | null = currentInstance
) {
injectHook(LifecycleHooks.UNMOUNTED, hook, target)
2019-05-28 19:36:15 +08:00
}
export function onRenderTriggered(
hook: Function,
target: ComponentInstance | null = currentInstance
) {
injectHook(LifecycleHooks.RENDER_TRIGGERED, hook, target)
2019-05-28 19:36:15 +08:00
}
export function onRenderTracked(
hook: Function,
target: ComponentInstance | null = currentInstance
) {
injectHook(LifecycleHooks.RENDER_TRACKED, hook, target)
2019-05-28 19:36:15 +08:00
}
export function onErrorCaptured(
hook: Function,
target: ComponentInstance | null = currentInstance
) {
injectHook(LifecycleHooks.ERROR_CAPTURED, hook, target)
2019-05-28 19:36:15 +08:00
}