From 73cdb9d4208f887fe08349657122e39175d7166c Mon Sep 17 00:00:00 2001 From: Evan You Date: Thu, 26 Nov 2020 09:25:35 -0500 Subject: [PATCH] fix(script-setup): ensure useContext() return valid context --- packages/runtime-core/src/apiSetupHelpers.ts | 12 ++++++++++-- packages/runtime-core/src/component.ts | 4 +++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/packages/runtime-core/src/apiSetupHelpers.ts b/packages/runtime-core/src/apiSetupHelpers.ts index fb8e6f7a169..719412ee074 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 2261dd81c90..935c4d3758f 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().`)