Skip to content

Commit 7177cf3

Browse files
committed
feat(runtime-core): add app.inject() API
1 parent 7bb9dd0 commit 7177cf3

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

packages/runtime-core/__tests__/apiCreateApp.spec.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,14 @@ describe('api: createApp', () => {
9393
app.provide('foo', 1)
9494
app.provide('bar', 2)
9595

96+
const foo = app.inject('foo')
97+
const bar = app.inject('bar')
98+
app.inject('non-existant')
99+
100+
expect('[Vue warn]: injection "non-existant" not found.').toHaveBeenWarned()
101+
expect(foo).toBe(1)
102+
expect(bar).toBe(2)
103+
96104
const root = nodeOps.createElement('div')
97105
app.mount(root)
98106
expect(serializeInner(root)).toBe(`3,2`)

packages/runtime-core/src/apiCreateApp.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ export interface App<HostElement = any> {
4141
): ComponentPublicInstance
4242
unmount(): void
4343
provide<T>(key: InjectionKey<T> | string, value: T): this
44+
inject<T>(key: InjectionKey<T> | string): T | undefined
4445

4546
// internal, but we need to expose these for the server-renderer and devtools
4647
_uid: number
@@ -346,6 +347,14 @@ export function createAppAPI<HostElement>(
346347
context.provides[key as string] = value
347348

348349
return app
350+
},
351+
352+
inject<T>(key: InjectionKey<T> | string) {
353+
const value = context.provides[key as string]
354+
if (__DEV__ && !((key as string) in context.provides)) {
355+
warn(`injection "${String(key)}" not found.`)
356+
}
357+
return value
349358
}
350359
})
351360

0 commit comments

Comments
 (0)