diff --git a/packages/runtime-core/src/apiSetupHelpers.ts b/packages/runtime-core/src/apiSetupHelpers.ts index fb8e6f7a..719412ee 100644 --- a/packages/runtime-core/src/apiSetupHelpers.ts +++ b/packages/runtime-core/src/apiSetupHelpers.ts @@ -1,4 +1,8 @@ -import { getCurrentInstance, SetupContext } from './component' +import { + getCurrentInstance, + SetupContext, + createSetupContext +} from './component' import { EmitFn, EmitsOptions } from './componentEmits' import { ComponentObjectPropsOptions, ExtractPropTypes } from './componentProps' import { warn } from './warning' @@ -53,5 +57,9 @@ export function defineEmit(emitOptions?: any) { } export function useContext(): SetupContext { - return getCurrentInstance()!.setupContext! + const i = getCurrentInstance()! + if (__DEV__ && !i) { + warn(`useContext() called without active instance.`) + } + return i.setupContext || (i.setupContext = createSetupContext(i)) } diff --git a/packages/runtime-core/src/component.ts b/packages/runtime-core/src/component.ts index 2261dd81..935c4d37 100644 --- a/packages/runtime-core/src/component.ts +++ b/packages/runtime-core/src/component.ts @@ -746,7 +746,9 @@ const attrHandlers: ProxyHandler = { } } -function createSetupContext(instance: ComponentInternalInstance): SetupContext { +export function createSetupContext( + instance: ComponentInternalInstance +): SetupContext { const expose: SetupContext['expose'] = exposed => { if (__DEV__ && instance.exposed) { warn(`expose() should be called only once per setup().`)