Skip to content

Commit 111d04f

Browse files
authored
fix(runtime-core): prevent self-injection (#2424)
fix #2400
1 parent 314ab2c commit 111d04f

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

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

+15
Original file line numberDiff line numberDiff line change
@@ -303,4 +303,19 @@ describe('api: provide/inject', () => {
303303
render(h(Provider), root)
304304
expect(`injection "foo" not found.`).not.toHaveBeenWarned()
305305
})
306+
307+
// #2400
308+
it('should not self-inject', () => {
309+
const Comp = {
310+
setup() {
311+
provide('foo', 'foo')
312+
const injection = inject('foo', null)
313+
return () => injection
314+
}
315+
}
316+
317+
const root = nodeOps.createElement('div')
318+
render(h(Comp), root)
319+
expect(serialize(root)).toBe(`<div><!----></div>`)
320+
})
306321
})

packages/runtime-core/src/apiInject.ts

+9-2
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,15 @@ export function inject(
4747
// a functional component
4848
const instance = currentInstance || currentRenderingInstance
4949
if (instance) {
50-
const provides = instance.provides
51-
if ((key as string | symbol) in provides) {
50+
// #2400
51+
// to support `app.use` plugins,
52+
// fallback to appContext's `provides` if the intance is at root
53+
const provides =
54+
instance.parent == null
55+
? instance.vnode.appContext && instance.vnode.appContext.provides
56+
: instance.parent.provides
57+
58+
if (provides && (key as string | symbol) in provides) {
5259
// TS doesn't allow symbol as index type
5360
return provides[key as string]
5461
} else if (arguments.length > 1) {

0 commit comments

Comments
 (0)