mirror of
https://github.com/robonen/tools.git
synced 2026-03-20 02:44:45 +00:00
refactor(packages/vue): use another way to provide state at app level in useContextFactory
This commit is contained in:
@@ -13,6 +13,8 @@
|
||||
* sleep(1000).then(() => {
|
||||
* console.log('Hello, World!');
|
||||
* });
|
||||
*
|
||||
* @since 0.0.3
|
||||
*/
|
||||
export function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
@@ -72,7 +72,7 @@ describe('useContextFactory', () => {
|
||||
|
||||
const childComponent = mount(Child, {
|
||||
global: {
|
||||
plugins: [app => context.provide('test', app)],
|
||||
plugins: [app => context.appProvide(app)('test')],
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import {inject, provide, type InjectionKey, type App} from 'vue';
|
||||
import { inject, provide, type InjectionKey, type App } from 'vue';
|
||||
import { VueToolsError } from '../..';
|
||||
|
||||
/**
|
||||
* @name useContextFactory
|
||||
* @category Utilities
|
||||
* @category State
|
||||
* @description A composable that provides a factory for creating context with unique key
|
||||
*
|
||||
* @param {string} name The name of the context
|
||||
* @returns {Object} An object with `inject`, `provide` and `key` properties
|
||||
* @returns {Object} An object with `inject`, `provide`, `appProvide` and `key` properties
|
||||
* @throws {VueToolsError} when the context is not provided
|
||||
*
|
||||
* @example
|
||||
@@ -17,12 +17,12 @@ import { VueToolsError } from '../..';
|
||||
* const value = inject();
|
||||
*
|
||||
* @example
|
||||
* const { inject: injectContext, provide: provideContext } = useContextFactory('MyContext');
|
||||
* const { inject: injectContext, appProvide } = useContextFactory('MyContext');
|
||||
*
|
||||
* // In a plugin
|
||||
* {
|
||||
* install(app) {
|
||||
* provideContext('Hello World', app);
|
||||
* appProvide(app)('Hello World');
|
||||
* }
|
||||
* }
|
||||
*
|
||||
@@ -38,19 +38,25 @@ export function useContextFactory<ContextValue>(name: string) {
|
||||
const context = inject(injectionKey, fallback);
|
||||
|
||||
if (context !== undefined)
|
||||
return context;
|
||||
return context;
|
||||
|
||||
throw new VueToolsError(`useContextFactory: '${name}' context is not provided`);
|
||||
};
|
||||
|
||||
const provideContext = (context: ContextValue, app?: App) => {
|
||||
(app?.provide ?? provide)(injectionKey, context);
|
||||
const provideContext = (context: ContextValue) => {
|
||||
provide(injectionKey, context);
|
||||
return context;
|
||||
};
|
||||
|
||||
const appProvide = (app: App) => (context: ContextValue) => {
|
||||
app.provide(injectionKey, context);
|
||||
return context;
|
||||
};
|
||||
|
||||
return {
|
||||
inject: injectContext,
|
||||
provide: provideContext,
|
||||
appProvide,
|
||||
key: injectionKey,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user