diff --git a/packages/runtime-core/__tests__/apiInject.spec.ts b/packages/runtime-core/__tests__/apiInject.spec.ts index f4bf2758fb0..87a415aa972 100644 --- a/packages/runtime-core/__tests__/apiInject.spec.ts +++ b/packages/runtime-core/__tests__/apiInject.spec.ts @@ -7,7 +7,8 @@ import { nextTick, Ref, readonly, - reactive + reactive, + defineComponent } from '../src/index' import { render, nodeOps, serialize } from '@vue/runtime-test' @@ -91,6 +92,34 @@ describe('api: provide/inject', () => { expect(serialize(root)).toBe(`
foobar
`) }) + it('bound to instance', () => { + const Provider = { + setup() { + return () => h(Consumer) + } + } + + const Consumer = defineComponent({ + name: 'Consumer', + inject: { + foo: { + from: 'foo', + default() { + return this!.$options.name + } + } + }, + render() { + // @ts-ignore + return this.foo + } + }) + + const root = nodeOps.createElement('div') + render(h(Provider), root) + expect(serialize(root)).toBe(`
Consumer
`) + }) + it('nested providers', () => { const ProviderOne = { setup() { diff --git a/packages/runtime-core/src/apiInject.ts b/packages/runtime-core/src/apiInject.ts index a1ec6126be6..1cf5771c582 100644 --- a/packages/runtime-core/src/apiInject.ts +++ b/packages/runtime-core/src/apiInject.ts @@ -60,7 +60,7 @@ export function inject( return provides[key as string] } else if (arguments.length > 1) { return treatDefaultAsFactory && isFunction(defaultValue) - ? defaultValue() + ? defaultValue.call(instance.proxy) : defaultValue } else if (__DEV__) { warn(`injection "${String(key)}" not found.`)