Browse Source

upd(form): add try catch ,fix submit method

richard1015 3 years ago
parent
commit
2e6098beb4

+ 48 - 38
src/packages/__VUE/form/common.ts

@@ -1,5 +1,5 @@
 import { getPropByPath, isObject, isPromise } from '@/packages/utils/util';
-import { computed, provide, reactive, VNode, watch } from 'vue';
+import { computed, PropType, provide, reactive, VNode, watch } from 'vue';
 import { FormItemRule } from '../formitem/types';
 import { ErrorMessage, FormRule, FormRules } from './types';
 
@@ -10,7 +10,7 @@ export const component = {
       default: {}
     },
     rules: {
-      type: Object,
+      type: Object as PropType<import('./types').FormRules>,
       default: {}
     }
   },
@@ -20,7 +20,7 @@ export const component = {
   setup(props: any, { emit, slots }: any) {
     const formErrorTip = computed(() => reactive<any>({}));
     provide('formErrorTip', formErrorTip);
-    const clearErrorTips = (value = props.modelValue) => {
+    const clearErrorTips = () => {
       Object.keys(formErrorTip.value).forEach((item) => {
         formErrorTip.value[item] = '';
       });
@@ -32,15 +32,15 @@ export const component = {
 
     watch(
       () => props.modelValue,
-      (value: any) => {
-        clearErrorTips(value);
+      () => {
+        clearErrorTips();
       },
       { immediate: true }
     );
 
     const findFormItem = (vnodes: VNode[]) => {
       let task: FormRule[] = [];
-      vnodes.forEach((vnode: VNode, index: number) => {
+      vnodes.forEach((vnode: VNode) => {
         let type = vnode.type;
         type = (type as any).name || type;
         if (type == 'nut-form-item' || type?.toString().endsWith('form-item')) {
@@ -73,8 +73,12 @@ export const component = {
 
       const _Promise = (errorMsg: ErrorMessage): Promise<ErrorMessage> => {
         return new Promise((resolve, reject) => {
-          tipMessage(errorMsg);
-          resolve(errorMsg);
+          try {
+            tipMessage(errorMsg);
+            resolve(errorMsg);
+          } catch (error) {
+            reject(error);
+          }
         });
       };
 
@@ -94,7 +98,7 @@ export const component = {
         const { required, regex, message } = ruleWithoutValidator;
         const errorMsg = { prop, message };
         if (required) {
-          if (value === '' || value === undefined || value === null) {
+          if (!value) {
             return _Promise(errorMsg);
           }
         }
@@ -105,14 +109,16 @@ export const component = {
           const result = validator(value, ruleWithoutValidator);
           if (isPromise(result)) {
             return new Promise((r, j) => {
-              result.then((res) => {
-                if (!res) {
-                  tipMessage(errorMsg);
-                  r(errorMsg);
-                } else {
-                  r(true);
-                }
-              });
+              result
+                .then((res) => {
+                  if (!res) {
+                    tipMessage(errorMsg);
+                    r(errorMsg);
+                  } else {
+                    r(true);
+                  }
+                })
+                .catch((e) => j(e));
             });
           } else {
             if (!result) {
@@ -131,35 +137,39 @@ export const component = {
      */
     const validate = (customProp = '') => {
       return new Promise((resolve, reject) => {
-        const task = findFormItem(slots.default());
+        try {
+          const task = findFormItem(slots.default());
 
-        const errors = task.map((item) => {
-          if (customProp) {
-            if (customProp == item.prop) {
-              return checkRule(item);
+          const errors = task.map((item) => {
+            if (customProp) {
+              if (customProp == item.prop) {
+                return checkRule(item);
+              } else {
+                return Promise.resolve(true);
+              }
             } else {
-              return Promise.resolve(true);
+              return checkRule(item);
             }
-          } else {
-            return checkRule(item);
-          }
-        });
+          });
 
-        Promise.all(errors).then((errorRes) => {
-          errorRes = errorRes.filter((item) => item != true);
-          const res = { valid: true, errors: [] };
-          if (errorRes.length) {
-            res.valid = false;
-            res.errors = errorRes as any;
-          }
-          resolve(res);
-        });
+          Promise.all(errors).then((errorRes) => {
+            errorRes = errorRes.filter((item) => item != true);
+            const res = { valid: true, errors: [] };
+            if (errorRes.length) {
+              res.valid = false;
+              res.errors = errorRes as any;
+            }
+            resolve(res);
+          });
+        } catch (error) {
+          reject(error);
+        }
       });
     };
-    const onSubmit = () => {
+    const submit = () => {
       validate();
       return false;
     };
-    return { validate, reset, onSubmit, formErrorTip };
+    return { validate, reset, submit, formErrorTip };
   }
 };

+ 1 - 0
src/packages/__VUE/form/demo.vue

@@ -295,6 +295,7 @@ export default createDemo({
             if (valid) {
               console.log('success', dynamicForm);
             } else {
+              Toast.warn(errors[0].message);
               console.log('error submit!!', errors);
             }
           });

+ 8 - 3
src/packages/__VUE/form/doc.en-US.md

@@ -75,6 +75,7 @@ app.use(CellGroup);
 </template>
 <script lang="ts">
 import { ref,reactive } from 'vue';
+import { Toast } from '@nutui/nutui';
 export default {
   setup(){
     const dynamicRefForm = ref<any>(null);
@@ -93,6 +94,7 @@ export default {
             if (valid) {
               console.log('success', dynamicForm);
             } else {
+              Toast.warn(errors[0].message);
               console.log('error submit!!', errors);
             }
           });
@@ -163,6 +165,7 @@ export default {
 </template>
 <script lang="ts">
 import { ref,reactive } from 'vue';
+import { Toast } from '@nutui/nutui';
 export default {
 setup(){
     const formData = reactive({
@@ -346,6 +349,7 @@ setup(){
 | Attribute   | Description                                              | Type   | Default |
 |-------------|----------------------------------------------------------|--------|---------|
 | model-value | Form data object (required when using form verification) | object |         |
+| rules`v3.2.3` | Unified configuration FormItem attr rules  | { prop: FormItemRule[] } |  {}      |
 
 ### Form Events
 
@@ -359,6 +363,7 @@ setup(){
 |---------------------|---------------------------------------------------------------------------------------------|------------------|---------|
 | required            | Whether to display the red asterisk next to the label of the required field                 | boolean          | `false` |
 | prop                | The v-model field of the form field is required when the form verification function is used | string           | -       |
+| rules               | Define validation rules                                                                     | FormItemRule []  | []      |
 | label-width         | The width of the form item label. The default unit is `px`                                  | number \| string | `90px`  |
 | label-align         | Form item label alignment. The optional values are `center` `right`                         | string           | `left`  |
 | body-align          | Default Solt box alignment. The optional values are `center` `right`                               | string           | `left`  |
@@ -366,7 +371,7 @@ setup(){
 | show-error-line     | Whether to mark the input box in red when the verification fails                            | boolean          | `true`  |
 | show-error-message  | Whether to display the error prompt under the input box when the verification fails         | boolean          | `true`  |
 
-### FormItem Rule data structure
+### FormItemRule data structure
 
 Use the `rules` attribute of FormItem to define verification rules. The optional attributes are as follows:
 
@@ -374,7 +379,7 @@ Use the `rules` attribute of FormItem to define verification rules. The optional
 |-----------|------------------------------------|-----------------------------------------|
 | required  | Is it a required field             | boolean                                 |
 | message   | Error prompt copy                  | string                                  |
-| validator | Verification by function           | (value) => boolean \| string \| Promise |
+| validator | Verification by function           | (value:string,rule?:FormItemRule) => boolean \| string \| Promise |
 | regex     | Verification by regular expression | RegExp                                  |
 
 ### FormItem Slots
@@ -398,6 +403,6 @@ Use [ref](https://vuejs.org/guide/essentials/template-refs.html#template-refs) t
 
 | Name              | Description                                                                                                       | Arguments                   | Return value |
 |-------------------|-------------------------------------------------------------------------------------------------------------------|-----------------------------|--------------|
-| submit            | Method of submitting form for verification                                                                        | -                           | Promise      |
+| submit`v3.2.8`            | Method of submitting form for verification                                                                        | -                           | Promise      |
 | reset             | Clear verification results                                                                                        | -                           | -            |
 | validate`v3.1.13` | Active trigger verification is used to trigger when the user customizes the scene, such as blur and change events | Same as FormItem prop value | -            |

+ 9 - 4
src/packages/__VUE/form/doc.md

@@ -75,6 +75,7 @@ app.use(CellGroup);
 </template>
 <script lang="ts">
 import { ref,reactive } from 'vue';
+import { Toast } from '@nutui/nutui';
 export default {
   setup(){
     const dynamicRefForm = ref<any>(null);
@@ -93,6 +94,7 @@ export default {
             if (valid) {
               console.log('success', dynamicForm);
             } else {
+              Toast.warn(errors[0].message);
               console.log('error submit!!', errors);
             }
           });
@@ -163,6 +165,7 @@ export default {
 </template>
 <script lang="ts">
 import { ref,reactive } from 'vue';
+import { Toast } from '@nutui/nutui';
 export default {
 setup(){
     const formData = reactive({
@@ -346,6 +349,7 @@ setup(){
 | 参数        | 说明                                 | 类型   | 默认值 |
 |-------------|--------------------------------------|--------|--------|
 | model-value | 表单数据对象(使用表单校验时,_必填_) | object |        |
+| rules`v3.2.3` | 统一配置每个 FormItem 的 rules  | { prop: FormItemRule[] } |  {}      |
 
 ### Form Events
 
@@ -359,6 +363,7 @@ setup(){
 |---------------------|------------------------------------------------------------------|------------------|---------|
 | required            | 是否显示必填字段的标签旁边的红色星号                             | boolean          | `false` |
 | prop                | 表单域 v-model 字段, 在使用表单校验功能的情况下,该属性是必填的 | string           | -       |
+| rules               | 定义校验规则                                  | FormItemRule []          | [] |
 | label-width         | 表单项 label 宽度,默认单位为`px`                                | number \| string | `90px`  |
 | label-align         | 表单项 label 对齐方式,可选值为 `center` `right`                 | string           | `left`  |
 | body-align          | 右侧插槽对齐方式,可选值为 `center` `right`                        | string           | `left`  |
@@ -366,7 +371,7 @@ setup(){
 | show-error-line     | 是否在校验不通过时标红输入框                                     | boolean          | `true`  |
 | show-error-message  | 是否在校验不通过时在输入框下方展示错误提示                       | boolean          | `true`  |
 
-### FormItem Rule 数据结构
+### FormItemRule 数据结构
 
 使用 FormItem 的`rules`属性可以定义校验规则,可选属性如下:
 
@@ -374,7 +379,7 @@ setup(){
 |-----------|------------------------|-----------------------------------------|
 | required  | 是否为必选字段         | boolean                                 |
 | message   | 错误提示文案           | string                                  |
-| validator | 通过函数进行校验       | (value) => boolean \| string \| Promise |
+| validator | 通过函数进行校验       | (value:string, rule?:FormItemRule ) => boolean \| string \| Promise |
 | regex     | 通过正则表达式进行校验 | RegExp                                  |
 
 ### FormItem Slots
@@ -398,6 +403,6 @@ setup(){
 
 | 方法名            | 说明                                                               | 参数                | 返回值  |
 |-------------------|--------------------------------------------------------------------|---------------------|---------|
-| submit            | 提交表单进行校验的方法                                             | -                   | Promise |
+| submit`v3.2.8`    | 提交表单进行校验的方法                                               | -                   | - |
 | reset             | 清空校验结果                                                       | -                   | -       |
-| validate`v3.1.13` | 用户主动触发校验,用于用户自定义场景时触发,例如 blur、change 事件 | 同 FormItem prop 值 | -       |
+| validate`v3.1.13` | 用户主动触发校验,用于用户自定义场景时触发,例如 blur、change 事件 | 同 FormItem prop 值,不传值会校验全部 Rule | -       |