form.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { computed, ref, type ComputedRef } from "vue";
  2. import type { ClFormRule, ClFormValidateError } from "../types";
  3. import { useParent } from "@/cool";
  4. class UseForm {
  5. public formRef = ref<ClFormComponentPublicInstance | null>(null);
  6. public disabled: ComputedRef<boolean>;
  7. constructor() {
  8. // 获取 cl-form 实例
  9. if (this.formRef.value == null) {
  10. const ClForm = useParent<ClFormComponentPublicInstance>("cl-form");
  11. if (ClForm != null) {
  12. this.formRef.value = ClForm;
  13. }
  14. }
  15. // 监听表单是否禁用
  16. this.disabled = computed<boolean>(() => this.formRef.value?.disabled ?? false);
  17. }
  18. // 注册表单字段
  19. addField = (prop: string): void => {
  20. this.formRef.value!.addField(prop);
  21. };
  22. // 注销表单字段
  23. removeField = (prop: string): void => {
  24. this.formRef.value!.removeField(prop);
  25. };
  26. // 获取字段值
  27. getValue = (prop: string): any | null => {
  28. return this.formRef.value!.getValue(prop);
  29. };
  30. // 设置字段错误信息
  31. setError = (prop: string, error: string): void => {
  32. this.formRef.value!.setError(prop, error);
  33. };
  34. // 获取字段错误信息
  35. getError = (prop: string): string => {
  36. return this.formRef.value!.getError(prop);
  37. };
  38. // 移除字段错误信息
  39. removeError = (prop: string): void => {
  40. this.formRef.value!.removeError(prop);
  41. };
  42. // 清除所有错误信息
  43. clearErrors = (): void => {
  44. this.formRef.value!.clearErrors();
  45. };
  46. // 获取字段规则
  47. getRule = (prop: string): ClFormRule[] => {
  48. return this.formRef.value!.getRule(prop);
  49. };
  50. // 验证单个规则
  51. validateRule = (value: any | null, rule: ClFormRule): string | null => {
  52. return this.formRef.value!.validateRule(value, rule);
  53. };
  54. // 清除所有验证
  55. clearValidate = (): void => {
  56. this.formRef.value!.clearValidate();
  57. };
  58. // 验证单个字段
  59. validateField = (prop: string): string | null => {
  60. return this.formRef.value!.validateField(prop);
  61. };
  62. // 验证整个表单
  63. validate = (callback: (valid: boolean, errors: ClFormValidateError[]) => void): void => {
  64. this.formRef.value!.validate(callback);
  65. };
  66. }
  67. export function useForm() {
  68. return new UseForm();
  69. }