Skip to content

Commit 3f3b9c6

Browse files
committed
feat: support second target argument for lifecycle functions
1 parent 9566e63 commit 3f3b9c6

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

src/apis/lifecycle.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,14 @@ import {
44
getVueConstructor,
55
setCurrentInstance,
66
getCurrentInstance,
7+
ComponentInternalInstance,
78
} from '../runtimeContext'
89
import { currentVMInFn } from '../utils/helper'
910

1011
const genName = (name: string) => `on${name[0].toUpperCase() + name.slice(1)}`
1112
function createLifeCycle(lifeCyclehook: string) {
12-
return (callback: Function) => {
13-
const vm = currentVMInFn(genName(lifeCyclehook))
13+
return (callback: Function, target?: ComponentInternalInstance | null) => {
14+
const vm = currentVMInFn(genName(lifeCyclehook), target)
1415
return (
1516
vm && injectHookOption(getVueConstructor(), vm, lifeCyclehook, callback)
1617
)

src/utils/helper.ts

+12-5
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
11
import Vue, { VNode, ComponentOptions, VueConstructor } from 'vue'
22
import { ComponentInstance } from '../component'
3-
import { getCurrentInstance, getVueConstructor } from '../runtimeContext'
3+
import {
4+
ComponentInternalInstance,
5+
getCurrentInstance,
6+
getVueConstructor,
7+
} from '../runtimeContext'
48
import { warn } from './utils'
59

6-
export function currentVMInFn(hook: string): ComponentInstance | undefined {
7-
const vm = getCurrentInstance()
8-
if (__DEV__ && !vm) {
10+
export function currentVMInFn(
11+
hook: string,
12+
target?: ComponentInternalInstance | null
13+
): ComponentInstance | undefined {
14+
target = target || getCurrentInstance()
15+
if (__DEV__ && !target) {
916
warn(
1017
`${hook} is called when there is no active component instance to be ` +
1118
`associated with. ` +
1219
`Lifecycle injection APIs can only be used during execution of setup().`
1320
)
1421
}
15-
return vm?.proxy
22+
return target?.proxy
1623
}
1724

1825
export function defineComponentInstance<V extends Vue = Vue>(

0 commit comments

Comments
 (0)