@@ -425,13 +425,37 @@ function provide(key, value) {
425425 provides [ key ] = value ;
426426 }
427427}
428- function inject ( key ) {
428+ function inject ( key , defaultValue ) {
429429 const currentInstance = getCurrentInstance ( ) ;
430430 if ( currentInstance ) {
431431 const parentProvides = currentInstance . parent . provides ;
432- console . log ( key , parentProvides ) ;
433- return parentProvides [ key ] ;
432+ if ( key in parentProvides ) {
433+ return parentProvides [ key ] ;
434+ }
435+ else if ( defaultValue ) {
436+ return defaultValue ;
437+ }
438+ }
439+ }
440+ // 扩展的
441+ function useInject ( keys = [ ] , defaultValues = { } ) {
442+ const currentInstance = getCurrentInstance ( ) ;
443+ if ( currentInstance ) {
444+ const parentProvides = currentInstance . parent . provides ;
445+ return composeInjectValues ( parentProvides , keys , defaultValues ) ;
434446 }
447+ return { } ;
448+ }
449+ function composeInjectValues ( provides = { } , keys = [ ] , defaultValues = { } ) {
450+ return keys . reduce ( ( result , currentKey ) => {
451+ if ( currentKey in provides ) {
452+ result [ currentKey ] = provides [ currentKey ] ;
453+ }
454+ else if ( defaultValues [ currentKey ] ) {
455+ result [ currentKey ] = defaultValues [ currentKey ] ;
456+ }
457+ return result ;
458+ } , { } ) ;
435459}
436460
437- export { clearCurrentInstance , createApp , createComponentInstance , createTextVNode , createVNode , getCurrentInstance , h , inject , patch , provide , render , renderSlots , setCurrentInstance , setupComponent } ;
461+ export { clearCurrentInstance , createApp , createComponentInstance , createTextVNode , createVNode , getCurrentInstance , h , inject , patch , provide , render , renderSlots , setCurrentInstance , setupComponent , useInject } ;
0 commit comments