form.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { computed, ref, type ComputedRef } from "vue";
  2. import type { ClFormRule, ClFormValidateError } from "../types";
  3. import { useParent } from "@/cool";
  4. export class FormValidate {
  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>(() => {
  17. if (this.formRef.value == null) {
  18. return false;
  19. }
  20. return this.formRef.value.disabled;
  21. });
  22. }
  23. // 注册表单字段
  24. addField = (prop: string): void => {
  25. this.formRef.value!.addField(prop);
  26. };
  27. // 注销表单字段
  28. removeField = (prop: string): void => {
  29. this.formRef.value!.removeField(prop);
  30. };
  31. // 获取字段值
  32. getValue = (prop: string): any | null => {
  33. return this.formRef.value!.getValue(prop);
  34. };
  35. // 设置字段错误信息
  36. setError = (prop: string, error: string): void => {
  37. this.formRef.value!.setError(prop, error);
  38. };
  39. // 获取字段错误信息
  40. getError = (prop: string): string => {
  41. return this.formRef.value!.getError(prop);
  42. };
  43. // 移除字段错误信息
  44. removeError = (prop: string): void => {
  45. this.formRef.value!.removeError(prop);
  46. };
  47. // 清除所有错误信息
  48. clearErrors = (): void => {
  49. this.formRef.value!.clearErrors();
  50. };
  51. // 获取字段规则
  52. getRule = (prop: string): ClFormRule[] => {
  53. return this.formRef.value!.getRule(prop);
  54. };
  55. // 验证单个规则
  56. validateRule = (value: any | null, rule: ClFormRule): string | null => {
  57. return this.formRef.value!.validateRule(value, rule);
  58. };
  59. // 清除所有验证
  60. clearValidate = (): void => {
  61. this.formRef.value!.clearValidate();
  62. };
  63. // 验证单个字段
  64. validateField = (prop: string): string | null => {
  65. return this.formRef.value!.validateField(prop);
  66. };
  67. // 验证整个表单
  68. validate = (callback: (valid: boolean, errors: ClFormValidateError[]) => void): void => {
  69. this.formRef.value!.validate(callback);
  70. };
  71. }
  72. export const useForm = (): FormValidate => {
  73. return new FormValidate();
  74. };