cl-form.uvue 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <template>
  2. <view
  3. class="cl-form"
  4. :class="[
  5. `cl-form--label-${labelPosition}`,
  6. {
  7. 'cl-form--disabled': disabled
  8. },
  9. pt.className
  10. ]"
  11. >
  12. <slot></slot>
  13. </view>
  14. </template>
  15. <script setup lang="ts">
  16. import { computed, getCurrentInstance, nextTick, ref, watch, type PropType } from "vue";
  17. import { get, isEmpty, isString, parsePt, parseToObject, $t, t } from "@/.cool";
  18. import type { ClFormLabelPosition, ClFormRule, ClFormValidateError } from "../../types";
  19. import { usePage } from "../../hooks";
  20. defineOptions({
  21. name: "cl-form"
  22. });
  23. // 组件属性定义
  24. const props = defineProps({
  25. // 透传样式
  26. pt: {
  27. type: Object,
  28. default: () => ({})
  29. },
  30. // 表单数据模型
  31. modelValue: {
  32. type: Object as PropType<any>,
  33. default: () => ({})
  34. },
  35. // 表单规则
  36. rules: {
  37. type: Object as PropType<Map<string, ClFormRule[]>>,
  38. default: () => new Map<string, ClFormRule[]>()
  39. },
  40. // 标签位置
  41. labelPosition: {
  42. type: String as PropType<ClFormLabelPosition>,
  43. default: "top"
  44. },
  45. // 标签宽度
  46. labelWidth: {
  47. type: String,
  48. default: "70px"
  49. },
  50. // 是否显示必填星号
  51. showAsterisk: {
  52. type: Boolean,
  53. default: true
  54. },
  55. // 是否显示错误信息
  56. showMessage: {
  57. type: Boolean,
  58. default: true
  59. },
  60. // 是否禁用整个表单
  61. disabled: {
  62. type: Boolean,
  63. default: false
  64. },
  65. // 滚动到第一个错误位置
  66. scrollToError: {
  67. type: Boolean,
  68. default: true
  69. }
  70. });
  71. const { proxy } = getCurrentInstance()!;
  72. // cl-page 上下文
  73. const page = usePage();
  74. // 透传样式类型
  75. type PassThrough = {
  76. className?: string;
  77. };
  78. // 解析透传样式
  79. const pt = computed(() => parsePt<PassThrough>(props.pt));
  80. // 表单数据
  81. const data = ref({} as UTSJSONObject);
  82. // 表单字段错误信息
  83. const errors = ref(new Map<string, string>());
  84. // 表单字段集合
  85. const fields = ref(new Set<string>([]));
  86. // 标签位置
  87. const labelPosition = computed(() => props.labelPosition);
  88. // 标签宽度
  89. const labelWidth = computed(() => props.labelWidth);
  90. // 是否显示必填星号
  91. const showAsterisk = computed(() => props.showAsterisk);
  92. // 是否显示错误信息
  93. const showMessage = computed(() => props.showMessage);
  94. // 是否禁用整个表单
  95. const disabled = computed(() => props.disabled);
  96. // 错误信息锁定
  97. const errorLock = ref(false);
  98. // 设置字段错误信息
  99. function setError(prop: string, error: string) {
  100. if (errorLock.value) {
  101. return;
  102. }
  103. if (prop != "") {
  104. errors.value.set(prop, error);
  105. }
  106. }
  107. // 移除字段错误信息
  108. function removeError(prop: string) {
  109. if (prop != "") {
  110. errors.value.delete(prop);
  111. }
  112. }
  113. // 获取字段错误信息
  114. function getError(prop: string): string {
  115. if (prop != "") {
  116. return errors.value.get(prop) ?? "";
  117. }
  118. return "";
  119. }
  120. // 获得错误信息,并滚动到第一个错误位置
  121. async function getErrors(): Promise<ClFormValidateError[]> {
  122. return new Promise((resolve) => {
  123. // 错误信息
  124. const errs = [] as ClFormValidateError[];
  125. // 错误信息位置
  126. const tops = new Map<string, number>();
  127. // 完成回调,将错误信息添加到数组中
  128. function done() {
  129. tops.forEach((top, prop) => {
  130. errs.push({
  131. field: prop,
  132. message: getError(prop)
  133. });
  134. });
  135. // 滚动到第一个错误位置
  136. if (props.scrollToError && errs.length > 0) {
  137. page.scrollTo((tops.get(errs[0].field) ?? 0) + page.getScrollTop());
  138. }
  139. resolve(errs);
  140. }
  141. // 如果错误信息为空,直接返回
  142. if (errors.value.size == 0) {
  143. done();
  144. return;
  145. }
  146. nextTick(() => {
  147. let component = proxy;
  148. // #ifdef MP
  149. let num = 0; // 记录已处理的表单项数量
  150. // 并查找其错误节点的位置
  151. const deep = (el: any, index: number) => {
  152. // 遍历当前节点的所有子节点
  153. el?.$children.map((e: any) => {
  154. // 限制递归深度,防止死循环
  155. if (index < 5) {
  156. // 判断是否为 cl-form-item 组件且 prop 存在
  157. if (e.prop != null && e.$options.name == "cl-form-item") {
  158. // 如果该字段已注册到 fields 中,则计数加一
  159. if (fields.value.has(e.prop)) {
  160. num += 1;
  161. }
  162. // 查询该 cl-form-item 下是否有错误节点,并获取其位置信息
  163. uni.createSelectorQuery()
  164. .in(e)
  165. .select(".cl-form-item--error")
  166. .boundingClientRect((res) => {
  167. // 如果未获取到节点信息,直接返回
  168. if (res == null) {
  169. return;
  170. }
  171. // 记录该字段的错误节点 top 值
  172. tops.set(e.prop, (res as NodeInfo).top!);
  173. // 如果已处理的表单项数量达到总数,执行 done 回调
  174. if (num >= fields.value.size) {
  175. done();
  176. }
  177. })
  178. .exec();
  179. }
  180. // 递归查找子节点
  181. deep(e, index + 1);
  182. }
  183. });
  184. };
  185. deep(component, 0);
  186. // #endif
  187. // #ifndef MP
  188. uni.createSelectorQuery()
  189. .in(component)
  190. .selectAll(".cl-form-item--error")
  191. .boundingClientRect((res) => {
  192. (res as NodeInfo[]).map((e) => {
  193. tops.set((e.id ?? "").replace("cl-form-item-", ""), e.top ?? 0);
  194. });
  195. done();
  196. })
  197. .exec();
  198. // #endif
  199. });
  200. });
  201. }
  202. // 清除所有错误信息
  203. function clearErrors() {
  204. errors.value.clear();
  205. }
  206. // 获取字段值
  207. function getValue(prop: string): any | null {
  208. if (prop != "") {
  209. return get(data.value, prop, null);
  210. }
  211. return null;
  212. }
  213. // 获取字段规则
  214. function getRule(prop: string): ClFormRule[] {
  215. return props.rules.get(prop) ?? ([] as ClFormRule[]);
  216. }
  217. // 设置字段规则
  218. function setRule(prop: string, rules: ClFormRule[]) {
  219. if (prop != "" && !isEmpty(rules)) {
  220. props.rules.set(prop, rules);
  221. }
  222. }
  223. // 移除字段规则
  224. function removeRule(prop: string) {
  225. if (prop != "") {
  226. props.rules.delete(prop);
  227. }
  228. }
  229. // 注册表单字段
  230. function addField(prop: string, rules: ClFormRule[]) {
  231. if (prop != "") {
  232. fields.value.add(prop);
  233. setRule(prop, rules);
  234. }
  235. }
  236. // 注销表单字段
  237. function removeField(prop: string) {
  238. if (prop != "") {
  239. fields.value.delete(prop);
  240. removeRule(prop);
  241. removeError(prop);
  242. }
  243. }
  244. // 验证单个规则
  245. function validateRule(value: any | null, rule: ClFormRule): null | string {
  246. // 必填验证
  247. if (rule.required == true) {
  248. if (
  249. value == null ||
  250. (value == "" && isString(value)) ||
  251. (Array.isArray(value) && value.length == 0)
  252. ) {
  253. return rule.message ?? t("此字段为必填项");
  254. }
  255. }
  256. // 如果值为空且不是必填,直接通过
  257. if ((value == null || (value == "" && isString(value))) && rule.required != true) {
  258. return null;
  259. }
  260. // 最小长度验证
  261. if (rule.min != null) {
  262. if (typeof value == "number") {
  263. if ((value as number) < rule.min) {
  264. return rule.message ?? $t(`最小值为{min}`, { min: rule.min });
  265. }
  266. } else {
  267. const len = Array.isArray(value) ? value.length : `${value}`.length;
  268. if (len < rule.min) {
  269. return rule.message ?? $t(`最少需要{min}个字符`, { min: rule.min });
  270. }
  271. }
  272. }
  273. // 最大长度验证
  274. if (rule.max != null) {
  275. if (typeof value == "number") {
  276. if (value > rule.max) {
  277. return rule.message ?? $t(`最大值为{max}`, { max: rule.max });
  278. }
  279. } else {
  280. const len = Array.isArray(value) ? value.length : `${value}`.length;
  281. if (len > rule.max) {
  282. return rule.message ?? $t(`最多允许{max}个字符`, { max: rule.max });
  283. }
  284. }
  285. }
  286. // 正则验证
  287. if (rule.pattern != null) {
  288. if (!rule.pattern.test(`${value}`)) {
  289. return rule.message ?? t("格式不正确");
  290. }
  291. }
  292. // 自定义验证
  293. if (rule.validator != null) {
  294. const result = rule.validator(value);
  295. if (result != true) {
  296. return typeof result == "string" ? result : (rule.message ?? t("验证失败"));
  297. }
  298. }
  299. return null;
  300. }
  301. // 清除所有验证
  302. function clearValidate() {
  303. errorLock.value = true;
  304. nextTick(() => {
  305. clearErrors();
  306. errorLock.value = false;
  307. });
  308. }
  309. // 验证单个字段
  310. function validateField(prop: string): string | null {
  311. let error = null as string | null;
  312. if (prop != "") {
  313. const value = getValue(prop);
  314. const rules = getRule(prop);
  315. if (!isEmpty(rules)) {
  316. // 逐个验证规则
  317. rules.find((rule) => {
  318. const msg = validateRule(value, rule);
  319. if (msg != null) {
  320. error = msg;
  321. return true;
  322. }
  323. return false;
  324. });
  325. }
  326. // 移除错误信息
  327. removeError(prop);
  328. }
  329. if (error != null) {
  330. setError(prop, error!);
  331. }
  332. return error;
  333. }
  334. // 验证整个表单
  335. async function validate(callback: (valid: boolean, errors: ClFormValidateError[]) => void) {
  336. // 验证所有字段
  337. fields.value.forEach((prop) => {
  338. validateField(prop);
  339. });
  340. // 获取所有错误信息,并滚动到第一个错误位置
  341. const errs = await getErrors();
  342. // 回调
  343. callback(errs.length == 0, errs);
  344. }
  345. watch(
  346. computed(() => parseToObject(props.modelValue)),
  347. (val: UTSJSONObject) => {
  348. data.value = val;
  349. },
  350. {
  351. immediate: true,
  352. deep: true
  353. }
  354. );
  355. defineExpose({
  356. labelPosition,
  357. labelWidth,
  358. showAsterisk,
  359. showMessage,
  360. disabled,
  361. data,
  362. errors,
  363. fields,
  364. addField,
  365. removeField,
  366. getValue,
  367. setError,
  368. getError,
  369. getErrors,
  370. removeError,
  371. clearErrors,
  372. getRule,
  373. setRule,
  374. removeRule,
  375. validateRule,
  376. clearValidate,
  377. validateField,
  378. validate
  379. });
  380. </script>
  381. <style lang="scss" scoped>
  382. .cl-form {
  383. @apply w-full;
  384. }
  385. </style>