Skip to content

Commit

Permalink
feat: support second target argument for lifecycle functions
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Aug 9, 2021
1 parent 9566e63 commit 3f3b9c6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
5 changes: 3 additions & 2 deletions src/apis/lifecycle.ts
Expand Up @@ -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)
)
Expand Down
17 changes: 12 additions & 5 deletions 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<V extends Vue = Vue>(
Expand Down

0 comments on commit 3f3b9c6

Please sign in to comment.