diff --git a/src/apis/lifecycle.ts b/src/apis/lifecycle.ts index 7d15b8bb..a8ffc541 100644 --- a/src/apis/lifecycle.ts +++ b/src/apis/lifecycle.ts @@ -4,13 +4,14 @@ import { getVueConstructor, setCurrentInstance, getCurrentInstance, + ComponentInternalInstance, } from '../runtimeContext' import { currentVMInFn } from '../utils/helper' const genName = (name: string) => `on${name[0].toUpperCase() + name.slice(1)}` function createLifeCycle(lifeCyclehook: string) { - return (callback: Function) => { - const vm = currentVMInFn(genName(lifeCyclehook)) + return (callback: Function, target?: ComponentInternalInstance | null) => { + const vm = currentVMInFn(genName(lifeCyclehook), target) return ( vm && injectHookOption(getVueConstructor(), vm, lifeCyclehook, callback) ) diff --git a/src/utils/helper.ts b/src/utils/helper.ts index 753bc907..c83dc7ce 100644 --- a/src/utils/helper.ts +++ b/src/utils/helper.ts @@ -1,18 +1,25 @@ import Vue, { VNode, ComponentOptions, VueConstructor } from 'vue' import { ComponentInstance } from '../component' -import { getCurrentInstance, getVueConstructor } from '../runtimeContext' +import { + ComponentInternalInstance, + getCurrentInstance, + getVueConstructor, +} from '../runtimeContext' import { warn } from './utils' -export function currentVMInFn(hook: string): ComponentInstance | undefined { - const vm = getCurrentInstance() - if (__DEV__ && !vm) { +export function currentVMInFn( + hook: string, + target?: ComponentInternalInstance | null +): ComponentInstance | undefined { + target = target || getCurrentInstance() + if (__DEV__ && !target) { warn( `${hook} is called when there is no active component instance to be ` + `associated with. ` + `Lifecycle injection APIs can only be used during execution of setup().` ) } - return vm?.proxy + return target?.proxy } export function defineComponentInstance(