Skip to content

Commit 17d3fc1

Browse files
authored
fix(inject): allow default value to be undefined (#930)
1 parent d8a8681 commit 17d3fc1

File tree

2 files changed

+34
-9
lines changed

2 files changed

+34
-9
lines changed

src/apis/inject.ts

+6-8
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,11 @@ export function inject(
7474
const val = resolveInject(key, vm)
7575
if (val !== NOT_FOUND) {
7676
return val
77+
} else if (arguments.length > 1) {
78+
return treatDefaultAsFactory && isFunction(defaultValue)
79+
? defaultValue()
80+
: defaultValue
81+
} else if (__DEV__) {
82+
warn(`Injection "${String(key)}" not found.`, vm)
7783
}
78-
79-
if (defaultValue === undefined && __DEV__) {
80-
warn(`Injection "${String(key)}" not found`, vm)
81-
}
82-
83-
return treatDefaultAsFactory && isFunction(defaultValue)
84-
? defaultValue()
85-
: defaultValue
8684
}

test/v3/runtime-core/apiInject.spec.ts

+28-1
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ describe('api: provide/inject', () => {
239239
const root = document.createElement('div')
240240
const vm = createApp(Provider).mount(root)
241241
expect(vm.$el.outerHTML).toBe(`<div></div>`)
242-
expect(`[Vue warn]: Injection "foo" not found`).toHaveBeenWarned()
242+
expect(`[Vue warn]: Injection "foo" not found.`).toHaveBeenWarned()
243243
})
244244

245245
it('should warn unfound w/ injectionKey is undefined', () => {
@@ -277,4 +277,31 @@ describe('api: provide/inject', () => {
277277
const vm = createApp(Comp).mount(root)
278278
expect(vm.$el.outerHTML).toBe(`<div>foo</div>`)
279279
})
280+
281+
it('should not warn when default value is undefined', () => {
282+
const Provider = {
283+
setup() {
284+
provide('foo', undefined)
285+
return () => h(Middle)
286+
},
287+
}
288+
289+
const Middle = {
290+
setup() {
291+
return () => h(Consumer)
292+
},
293+
}
294+
295+
const Consumer = {
296+
setup() {
297+
const foo = inject('foo')
298+
return () => h('div', foo as unknown as string)
299+
},
300+
}
301+
302+
const root = document.createElement('div')
303+
const vm = createApp(Provider).mount(root)
304+
expect(vm.$el.outerHTML).toBe(`<div></div>`)
305+
expect(`injection "foo" not found.`).not.toHaveBeenWarned()
306+
})
280307
})

0 commit comments

Comments
 (0)