config.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import type { BaseFormComponentType, VbenFormAdapterOptions } from './types';
  2. import type { Component } from 'vue';
  3. import { h } from 'vue';
  4. import {
  5. VbenButton,
  6. VbenCheckbox,
  7. Input as VbenInput,
  8. VbenInputPassword,
  9. VbenPinInput,
  10. VbenSelect,
  11. } from '@vben-core/shadcn-ui';
  12. import { defineRule } from 'vee-validate';
  13. const DEFAULT_MODEL_PROP_NAME = 'modelValue';
  14. export const COMPONENT_MAP: Record<BaseFormComponentType, Component> = {
  15. DefaultResetActionButton: h(VbenButton, { size: 'sm', variant: 'outline' }),
  16. DefaultSubmitActionButton: h(VbenButton, { size: 'sm', variant: 'default' }),
  17. VbenCheckbox,
  18. VbenInput,
  19. VbenInputPassword,
  20. VbenPinInput,
  21. VbenSelect,
  22. };
  23. export const COMPONENT_BIND_EVENT_MAP: Partial<
  24. Record<BaseFormComponentType, string>
  25. > = {
  26. VbenCheckbox: 'checked',
  27. };
  28. export function setupVbenForm<
  29. T extends BaseFormComponentType = BaseFormComponentType,
  30. >(options: VbenFormAdapterOptions<T>) {
  31. const { components, config, defineRules } = options;
  32. if (defineRules) {
  33. for (const key of Object.keys(defineRules)) {
  34. defineRule(key, defineRules[key as never]);
  35. }
  36. }
  37. const baseModelPropName =
  38. config?.baseModelPropName ?? DEFAULT_MODEL_PROP_NAME;
  39. const modelPropNameMap = config?.modelPropNameMap as
  40. | Record<BaseFormComponentType, string>
  41. | undefined;
  42. for (const component of Object.keys(components)) {
  43. const key = component as BaseFormComponentType;
  44. COMPONENT_MAP[key] = components[component as never];
  45. if (baseModelPropName !== DEFAULT_MODEL_PROP_NAME) {
  46. COMPONENT_BIND_EVENT_MAP[key] = baseModelPropName;
  47. }
  48. // 覆盖特殊组件的modelPropName
  49. if (modelPropNameMap && modelPropNameMap[key]) {
  50. COMPONENT_BIND_EVENT_MAP[key] = modelPropNameMap[key];
  51. }
  52. }
  53. }