From: Hunter Date: Tue, 20 Oct 2020 00:45:48 +0000 (+0800) Subject: fix(runtime-core): prevent self-injection (#2424) X-Git-Tag: v3.0.2~8 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=111d04f119a2b2d0b1a1790a063b152c17787943;p=thirdparty%2Fvuejs%2Fcore.git fix(runtime-core): prevent self-injection (#2424) fix #2400 --- diff --git a/packages/runtime-core/__tests__/apiInject.spec.ts b/packages/runtime-core/__tests__/apiInject.spec.ts index 8498e4f848..bb21524878 100644 --- a/packages/runtime-core/__tests__/apiInject.spec.ts +++ b/packages/runtime-core/__tests__/apiInject.spec.ts @@ -303,4 +303,19 @@ describe('api: provide/inject', () => { render(h(Provider), root) expect(`injection "foo" not found.`).not.toHaveBeenWarned() }) + + // #2400 + it('should not self-inject', () => { + const Comp = { + setup() { + provide('foo', 'foo') + const injection = inject('foo', null) + return () => injection + } + } + + const root = nodeOps.createElement('div') + render(h(Comp), root) + expect(serialize(root)).toBe(`
`) + }) }) diff --git a/packages/runtime-core/src/apiInject.ts b/packages/runtime-core/src/apiInject.ts index c12b649084..186b411b24 100644 --- a/packages/runtime-core/src/apiInject.ts +++ b/packages/runtime-core/src/apiInject.ts @@ -47,8 +47,15 @@ export function inject( // a functional component const instance = currentInstance || currentRenderingInstance if (instance) { - const provides = instance.provides - if ((key as string | symbol) in provides) { + // #2400 + // to support `app.use` plugins, + // fallback to appContext's `provides` if the intance is at root + const provides = + instance.parent == null + ? instance.vnode.appContext && instance.vnode.appContext.provides + : instance.parent.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) {