From 3f3b9c6118eebf83b7a7c480d0c822b67081f7fb Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Mon, 9 Aug 2021 16:43:16 +0800 Subject: [PATCH] feat: support second target argument for lifecycle functions --- src/apis/lifecycle.ts | 5 +++-- src/utils/helper.ts | 17 ++++++++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) 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(