Explorar el Código

cl-form-item 支持配置 rules

icssoa hace 7 meses
padre
commit
ee20189d6e
Se han modificado 1 ficheros con 21 adiciones y 3 borrados
  1. 21 3
      uni_modules/cool-ui/components/cl-form-item/cl-form-item.uvue

+ 21 - 3
uni_modules/cool-ui/components/cl-form-item/cl-form-item.uvue

@@ -7,6 +7,7 @@
 			},
 			pt.className
 		]"
+		:id="`cl-form-item-${prop}`"
 	>
 		<view class="cl-form-item__inner" :class="[`is-${labelPosition}`, pt.inner?.className]">
 			<view
@@ -53,7 +54,7 @@
 <script setup lang="ts">
 import { computed, onMounted, onUnmounted, watch, type PropType } from "vue";
 import { isEqual, parseClass, parsePt } from "@/cool";
-import type { ClFormLabelPosition, PassThroughProps } from "../../types";
+import type { ClFormLabelPosition, ClFormRule, PassThroughProps } from "../../types";
 import { useForm } from "../../hooks";
 
 defineOptions({
@@ -81,6 +82,11 @@ const props = defineProps({
 		type: String,
 		default: ""
 	},
+	// 字段验证规则
+	rules: {
+		type: Array as PropType<ClFormRule[]>,
+		default: () => []
+	},
 	// 标签位置
 	labelPosition: {
 		type: String as PropType<ClFormLabelPosition>,
@@ -109,7 +115,7 @@ const props = defineProps({
 });
 
 // cl-form 上下文
-const { formRef, getError, getValue, validateField, addField, removeField } = useForm();
+const { formRef, getError, getValue, validateField, addField, removeField, setRule } = useForm();
 
 // 透传样式类型
 type PassThrough = {
@@ -165,7 +171,7 @@ watch(
 	computed(() => props.required),
 	(val: boolean) => {
 		if (val) {
-			addField(props.prop);
+			addField(props.prop, props.rules);
 		} else {
 			removeField(props.prop);
 		}
@@ -176,6 +182,7 @@ watch(
 );
 
 onMounted(() => {
+	// 监听字段值变化
 	watch(
 		computed(() => {
 			const value = getValue(props.prop);
@@ -197,6 +204,17 @@ onMounted(() => {
 			deep: true
 		}
 	);
+
+	// 监听规则变化
+	watch(
+		computed(() => props.rules),
+		(val: ClFormRule[]) => {
+			setRule(props.prop, val);
+		},
+		{
+			deep: true
+		}
+	);
 });
 
 onUnmounted(() => {