Skip to content

Commit 78592bf

Browse files
authoredSep 7, 2020
feat(inject): add treatDefaultAsFactory argument (#503)
1 parent 026a78a commit 78592bf

File tree

2 files changed

+34
-6
lines changed

2 files changed

+34
-6
lines changed
 

‎src/apis/inject.ts

+13-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { ComponentInstance } from '../component'
2-
import { hasOwn, warn, currentVMInFn } from '../utils'
2+
import { hasOwn, warn, currentVMInFn, isFunction } from '../utils'
33
import { getCurrentInstance } from '../runtimeContext'
44

55
const NOT_FOUND = {}
@@ -38,10 +38,15 @@ export function provide<T>(key: InjectionKey<T> | string, value: T): void {
3838
}
3939

4040
export function inject<T>(key: InjectionKey<T> | string): T | undefined
41-
export function inject<T>(key: InjectionKey<T> | string, defaultValue: T): T
41+
export function inject<T>(
42+
key: InjectionKey<T> | string,
43+
defaultValue: T,
44+
treatDefaultAsFactory?: boolean
45+
): T
4246
export function inject(
4347
key: InjectionKey<any> | string,
44-
defaultValue?: unknown
48+
defaultValue?: unknown,
49+
treatDefaultAsFactory = false
4550
) {
4651
if (!key) {
4752
return defaultValue
@@ -55,12 +60,14 @@ export function inject(
5560

5661
const val = resolveInject(key, vm)
5762
if (val !== NOT_FOUND) {
58-
return val;
63+
return val
5964
}
60-
65+
6166
if (defaultValue === undefined && __DEV__) {
6267
warn(`Injection "${String(key)}" not found`, vm)
6368
}
6469

65-
return defaultValue
70+
return treatDefaultAsFactory && isFunction(defaultValue)
71+
? defaultValue()
72+
: defaultValue
6673
}

‎test/apis/inject.spec.js

+21
Original file line numberDiff line numberDiff line change
@@ -145,4 +145,25 @@ describe('Hooks provide/inject', () => {
145145
expect(obj1.msg).toBe('foo')
146146
expect(obj2.msg).toBe('bar')
147147
})
148+
149+
it('should call default value as factory', () => {
150+
const State = Symbol()
151+
let fn = jest.fn()
152+
new Vue({
153+
template: `<child/>`,
154+
setup() {},
155+
provide: {
156+
X: { msg: 'bar' },
157+
},
158+
components: {
159+
child: {
160+
setup() {
161+
inject(State, fn, true)
162+
},
163+
template: `<div/>`,
164+
},
165+
},
166+
}).$mount()
167+
expect(fn).toHaveBeenCalled()
168+
})
148169
})

0 commit comments

Comments
 (0)
Please sign in to comment.