import { computed, ref, type ComputedRef } from "vue"; import type { ClFormRule, ClFormValidateError } from "../types"; import { useParent } from "@/cool"; class UseForm { public formRef = ref(null); public disabled: ComputedRef; constructor() { // 获取 cl-form 实例 if (this.formRef.value == null) { const ClForm = useParent("cl-form"); if (ClForm != null) { this.formRef.value = ClForm; } } // 监听表单是否禁用 this.disabled = computed(() => this.formRef.value?.disabled ?? false); } // 注册表单字段 addField = (prop: string): void => { this.formRef.value!.addField(prop); }; // 注销表单字段 removeField = (prop: string): void => { this.formRef.value!.removeField(prop); }; // 获取字段值 getValue = (prop: string): any | null => { return this.formRef.value!.getValue(prop); }; // 设置字段错误信息 setError = (prop: string, error: string): void => { this.formRef.value!.setError(prop, error); }; // 获取字段错误信息 getError = (prop: string): string => { return this.formRef.value!.getError(prop); }; // 移除字段错误信息 removeError = (prop: string): void => { this.formRef.value!.removeError(prop); }; // 清除所有错误信息 clearErrors = (): void => { this.formRef.value!.clearErrors(); }; // 获取字段规则 getRule = (prop: string): ClFormRule[] => { return this.formRef.value!.getRule(prop); }; // 验证单个规则 validateRule = (value: any | null, rule: ClFormRule): string | null => { return this.formRef.value!.validateRule(value, rule); }; // 清除所有验证 clearValidate = (): void => { this.formRef.value!.clearValidate(); }; // 验证单个字段 validateField = (prop: string): string | null => { return this.formRef.value!.validateField(prop); }; // 验证整个表单 validate = (callback: (valid: boolean, errors: ClFormValidateError[]) => void): void => { this.formRef.value!.validate(callback); }; } export function useForm() { return new UseForm(); }