Skip to content

Commit

Permalink
chore: refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Apr 5, 2023
1 parent 2b3e6c6 commit afed3c3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 13 deletions.
5 changes: 3 additions & 2 deletions packages/runtime-core/src/apiCreateApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ export function createAppAPI<HostElement>(
},

runWithContext(fn) {
currentApp = this
currentApp = app
try {
return fn()
} finally {
Expand All @@ -399,6 +399,7 @@ export function createAppAPI<HostElement>(
}

/**
* @internal Used to identify the current app when using `inject()` within `app.runWithContext()`.
* @internal Used to identify the current app when using `inject()` within
* `app.runWithContext()`.
*/
export let currentApp: App<unknown> | null = null
19 changes: 8 additions & 11 deletions packages/runtime-core/src/apiInject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { currentInstance } from './component'
import { currentRenderingInstance } from './componentRenderContext'
import { currentApp } from './apiCreateApp'
import { warn } from './warning'
import { ComponentPublicInstance } from './componentPublicInstance'

export interface InjectionKey<T> extends Symbol {}

Expand Down Expand Up @@ -46,28 +45,26 @@ export function inject(
treatDefaultAsFactory = false
) {
// fallback to `currentRenderingInstance` so that this can be called in
// a functional component and to currentApp so it can be called within `app.runWithContext()`
const instance = currentInstance || currentRenderingInstance || currentApp
// a functional component
const instance = currentInstance || currentRenderingInstance

if (instance) {
// also support looking up from app-level provides w/ `app.runWithContext()`
if (instance || currentApp) {
// #2400
// to support `app.use` plugins,
// fallback to appContext's `provides` if the instance is at root
const provides =
'mount' in instance // checks if instance is an App
? instance._context.provides
: instance.parent == null
const provides = instance
? instance.parent == null
? instance.vnode.appContext && instance.vnode.appContext.provides
: instance.parent.provides
: currentApp!._context.provides

if (provides && (key as string | symbol) in provides) {
// TS doesn't allow symbol as index type
return provides[key as string]
} else if (arguments.length > 1) {
return treatDefaultAsFactory && isFunction(defaultValue)
? defaultValue.call(
(instance as { proxy?: ComponentPublicInstance | null }).proxy
)
? defaultValue.call(instance && instance.proxy)
: defaultValue
} else if (__DEV__) {
warn(`injection "${String(key)}" not found.`)
Expand Down

0 comments on commit afed3c3

Please sign in to comment.