]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(runtime-core): prevent self-injection (#2424)
authorHunter <kltan69@gmail.com>
Tue, 20 Oct 2020 00:45:48 +0000 (08:45 +0800)
committerGitHub <noreply@github.com>
Tue, 20 Oct 2020 00:45:48 +0000 (20:45 -0400)
fix #2400

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

index 8498e4f848fdf872a4ee9086984ef03977c90c66..bb21524878a5605d6f401dbdcfa1ee380c754195 100644 (file)
@@ -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(`<div><!----></div>`)
+  })
 })
index c12b6490849e7a262eae74afc3cb88dcc6ef2533..186b411b24148f38e0df9515682f977070fe92f5 100644 (file)
@@ -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) {