-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature(composable): create utility composable useHybridInject
- Loading branch information
1 parent
7f28d20
commit cb97e3e
Showing
2 changed files
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
26 changes: 26 additions & 0 deletions
26
packages/x-components/src/composables/use-hybrid-inject.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import { computed, ComputedRef, inject } from 'vue'; | ||
|
||
/** | ||
* Function to use a hybrid inject, which allows to inject a value provided by the regular provide | ||
* of vue or by the XProvide decorator. | ||
* | ||
* @param key - The key of the value to inject. | ||
* @param defaultValue - The default value to use if the value is not provided. | ||
* @returns The computed value of the injected value. | ||
*/ | ||
export function useHybridInject<SomeValue>( | ||
key: string, | ||
defaultValue?: SomeValue | ||
): ComputedRef<SomeValue | undefined> { | ||
type WrappedValue = { value: SomeValue }; | ||
|
||
return computed<SomeValue | undefined>(() => { | ||
const injectedValue = defaultValue | ||
? inject<SomeValue | WrappedValue>(key, defaultValue) | ||
: inject<SomeValue | WrappedValue>(key); | ||
|
||
return injectedValue && typeof injectedValue === 'object' && 'value' in injectedValue | ||
? injectedValue.value | ||
: injectedValue; | ||
}); | ||
} |