]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(script-setup): ensure useContext() return valid context
authorEvan You <yyx990803@gmail.com>
Thu, 26 Nov 2020 14:25:35 +0000 (09:25 -0500)
committerEvan You <yyx990803@gmail.com>
Thu, 26 Nov 2020 14:25:56 +0000 (09:25 -0500)
packages/runtime-core/src/apiSetupHelpers.ts
packages/runtime-core/src/component.ts

index fb8e6f7a169c6a254b1cf1d3f79c7f3c52f2ec14..719412ee074ba74a0405c29c711e19232e3bccda 100644 (file)
@@ -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))
 }
index 2261dd81c90c671dc3dbe00b77b362ee328e9a4a..935c4d3758fb4dd1dcf75d0c9d8ebf41395ca1c2 100644 (file)
@@ -746,7 +746,9 @@ const attrHandlers: ProxyHandler<Data> = {
   }
 }
 
-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().`)