feat(vue): expand @robonen/vue composable collection
Composables, tests, category barrels, and README for @robonen/vue.
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { defineComponent, h } from 'vue';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { useForm } from '../useForm';
|
||||
import type { UseFormReturn } from '../useForm';
|
||||
import { useFormContext } from '.';
|
||||
|
||||
describe(useFormContext, () => {
|
||||
it('returns null when no form is provided', () => {
|
||||
let ctx: UseFormReturn | null = null as UseFormReturn | null;
|
||||
|
||||
mount(defineComponent({
|
||||
setup() {
|
||||
ctx = useFormContext();
|
||||
return () => h('div');
|
||||
},
|
||||
}));
|
||||
|
||||
expect(ctx).toBeNull();
|
||||
});
|
||||
|
||||
it('injects the form provided by an ancestor', () => {
|
||||
let injected: UseFormReturn | null = null;
|
||||
let provided: UseFormReturn | undefined;
|
||||
|
||||
const Child = defineComponent({
|
||||
setup() {
|
||||
injected = useFormContext();
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
|
||||
const Parent = defineComponent({
|
||||
setup() {
|
||||
provided = useForm({ initialValues: { a: 1 } });
|
||||
return () => h(Child);
|
||||
},
|
||||
});
|
||||
|
||||
mount(Parent);
|
||||
|
||||
expect(injected).toBe(provided);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { injectFormContext } from '../useForm/context';
|
||||
import type { UseFormReturn } from '../useForm';
|
||||
|
||||
/**
|
||||
* @name useFormContext
|
||||
* @category Forms
|
||||
* @description Retrieve the {@link useForm} instance provided by an ancestor, for
|
||||
* building field components that live anywhere in the form's subtree. Returns
|
||||
* `null` when no form has been provided (so callers can support standalone use).
|
||||
*
|
||||
* @returns {UseFormReturn | null} The injected form instance, or `null`
|
||||
*
|
||||
* @example
|
||||
* // Inside a custom <TextField> rendered within a useForm() component:
|
||||
* const form = useFormContext();
|
||||
* if (form)
|
||||
* form.setFieldValue('email', 'a@b.com');
|
||||
*
|
||||
* @since 0.0.16
|
||||
*/
|
||||
export function useFormContext<TInput extends object = any, TOutput = TInput>(): UseFormReturn<TInput, TOutput> | null {
|
||||
return injectFormContext<TInput, TOutput>();
|
||||
}
|
||||
Reference in New Issue
Block a user