1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 10:54:44 +00:00

refactor(packages/vue): return object instead of tuple for useContextFactory

This commit is contained in:
2024-11-26 16:10:59 +07:00
parent 1823771b4a
commit 46ea487222
2 changed files with 13 additions and 9 deletions

View File

@@ -9,7 +9,7 @@ function testFactory<Data>(
context: ReturnType<typeof useContextFactory<Data>>, context: ReturnType<typeof useContextFactory<Data>>,
fallback?: Data, fallback?: Data,
) { ) {
const [inject, provide] = context; const { inject, provide } = context;
const Child = defineComponent({ const Child = defineComponent({
setup() { setup() {
@@ -72,7 +72,7 @@ describe('useContextFactory', () => {
const childComponent = mount(Child, { const childComponent = mount(Child, {
global: { global: {
plugins: [app => context[1]('test', app)], plugins: [app => context.provide('test', app)],
}, },
}); });

View File

@@ -7,17 +7,17 @@ import { VueToolsError } from '../..';
* @description A composable that provides a factory for creating context with unique key * @description A composable that provides a factory for creating context with unique key
* *
* @param {string} name The name of the context * @param {string} name The name of the context
* @returns {readonly [injectContext, provideContext]} The context factory * @returns {Object} An object with `inject`, `provide` and `key` properties
* @throws {VueToolsError} when the context is not provided * @throws {VueToolsError} when the context is not provided
* *
* @example * @example
* const [injectContext, provideContext] = useContextFactory('MyContext'); * const { inject, provide } = useContextFactory('MyContext');
* *
* const context = provideContext('Hello World'); * provide('Hello World');
* const value = injectContext(); * const value = inject();
* *
* @example * @example
* const [injectContext, provideContext] = useContextFactory('MyContext'); * const { inject: injectContext, provide: provideContext } = useContextFactory('MyContext');
* *
* // In a plugin * // In a plugin
* { * {
@@ -44,9 +44,13 @@ export function useContextFactory<ContextValue>(name: string) {
}; };
const provideContext = (context: ContextValue, app?: App) => { const provideContext = (context: ContextValue, app?: App) => {
(app ? app.provide : provide)(injectionKey, context); (app?.provide ?? provide)(injectionKey, context);
return context; return context;
}; };
return [injectContext, provideContext] as const; return {
inject: injectContext,
provide: provideContext,
key: injectionKey,
}
} }