vben
2020-11-01 84b8302c0921ea7fbcd1c42fa057b94660129857
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
<template>
  <Form v-bind="$attrs" ref="formElRef" :model="formModel">
    <Row :class="getProps.compact ? 'compact-form-row' : ''">
      <slot name="formHeader" />
      <template v-for="schema in getSchema" :key="schema.field">
        <FormItem
          :schema="schema"
          :formProps="getProps"
          :allDefaultValues="defaultValueRef"
          :formModel="formModel"
        >
          <template #[item]="data" v-for="item in Object.keys($slots)">
            <slot :name="item" v-bind="data" />
          </template>
        </FormItem>
      </template>
      <FormAction
        v-bind="{ ...getActionPropsRef, ...advanceState }"
        @toggle-advanced="handleToggleAdvanced"
      />
      <slot name="formFooter" />
    </Row>
  </Form>
</template>
<script lang="ts">
  import type { FormActionType, FormProps, FormSchema } from './types/form';
  import type { AdvanceState } from './types/hooks';
  import type { Ref } from 'vue';
  import type { ValidateFields } from 'ant-design-vue/lib/form/interface';
 
  import {
    defineComponent,
    reactive,
    ref,
    computed,
    unref,
    toRef,
    onMounted,
    watchEffect,
  } from 'vue';
  import { Form, Row } from 'ant-design-vue';
  import FormItem from './FormItem';
  import { basicProps } from './props';
  import FormAction from './FormAction';
 
  import { dateItemType } from './helper';
  import moment from 'moment';
  import { cloneDeep } from 'lodash-es';
  import { deepMerge } from '/@/utils';
 
  import { useFormValues } from './hooks/useFormValues';
  import useAdvanced from './hooks/useAdvanced';
  import { useFormAction } from './hooks/useFormAction';
 
  export default defineComponent({
    name: 'BasicForm',
    components: { FormItem, Form, Row, FormAction },
    inheritAttrs: false,
    props: basicProps,
    emits: ['advanced-change', 'reset', 'submit', 'register'],
    setup(props, { emit }) {
      const formModel = reactive({});
 
      const actionState = reactive({
        resetAction: {},
        submitAction: {},
      });
 
      const advanceState = reactive<AdvanceState>({
        isAdvanced: true,
        hideAdvanceBtn: false,
        isLoad: false,
        actionSpan: 6,
      });
 
      const defaultValueRef = ref<any>({});
      const propsRef = ref<Partial<FormProps>>({});
      const schemaRef = ref<FormSchema[] | null>(null);
      const formElRef = ref<Nullable<FormActionType>>(null);
 
      const getMergePropsRef = computed(
        (): FormProps => {
          return deepMerge(cloneDeep(props), unref(propsRef));
        }
      );
 
      // 获取表单基本配置
      const getProps = computed(
        (): FormProps => {
          return {
            ...unref(getMergePropsRef),
            resetButtonOptions: deepMerge(
              actionState.resetAction,
              unref(getMergePropsRef).resetButtonOptions || {}
            ),
            submitButtonOptions: deepMerge(
              actionState.submitAction,
              unref(getMergePropsRef).submitButtonOptions || {}
            ),
          };
        }
      );
 
      const getSchema = computed((): FormSchema[] => {
        const schemas: FormSchema[] = unref(schemaRef) || (unref(getProps).schemas as any);
        for (const schema of schemas) {
          const { defaultValue, component } = schema;
          if (defaultValue && dateItemType.includes(component!)) {
            schema.defaultValue = moment(defaultValue);
          }
        }
        return schemas as FormSchema[];
      });
 
      const { getActionPropsRef, handleToggleAdvanced } = useAdvanced({
        advanceState,
        emit,
        getMergePropsRef,
        getProps,
        getSchema,
        formModel,
        defaultValueRef,
      });
 
      const { handleFormValues, initDefault } = useFormValues({
        transformDateFuncRef: toRef(props, 'transformDateFunc') as Ref<Fn<any>>,
        fieldMapToTimeRef: toRef(props, 'fieldMapToTime'),
        defaultValueRef,
        getSchema,
        formModel,
      });
 
      const {
        // handleSubmit,
        setFieldsValue,
        clearValidate,
        validate,
        validateFields,
        getFieldsValue,
        updateSchema,
        appendSchemaByField,
        removeSchemaByFiled,
        resetFields,
      } = useFormAction({
        emit,
        getProps,
        formModel,
        getSchema,
        defaultValueRef,
        formElRef: formElRef as any,
        schemaRef: schemaRef as any,
        handleFormValues,
        actionState,
      });
 
      watchEffect(() => {
        if (!unref(getMergePropsRef).model) return;
        setFieldsValue(unref(getMergePropsRef).model);
      });
 
      /**
       * @description:设置表单
       */
      function setProps(formProps: Partial<FormProps>): void {
        const mergeProps = deepMerge(unref(propsRef) || {}, formProps);
        propsRef.value = mergeProps;
      }
 
      const methods: Partial<FormActionType> = {
        getFieldsValue,
        setFieldsValue,
        resetFields,
        updateSchema,
        setProps,
        removeSchemaByFiled,
        appendSchemaByField,
        clearValidate,
        validateFields: validateFields as ValidateFields,
        validate: validate as ValidateFields,
      };
 
      onMounted(() => {
        initDefault();
        emit('register', methods);
      });
 
      return {
        handleToggleAdvanced,
        formModel,
        getActionPropsRef,
        defaultValueRef,
        advanceState,
        getProps,
        formElRef,
        getSchema,
        ...methods,
      };
    },
  });
</script>