Skip to content

Commit

Permalink
fix(script-setup): ensure useContext() return valid context
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Nov 26, 2020
1 parent a764814 commit 73cdb9d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
12 changes: 10 additions & 2 deletions packages/runtime-core/src/apiSetupHelpers.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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))
}
4 changes: 3 additions & 1 deletion packages/runtime-core/src/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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().`)
Expand Down

0 comments on commit 73cdb9d

Please sign in to comment.