Przeglądaj źródła

perf(自增器): 增加自增减少内存leak

gemercheung 3 lat temu
rodzic
commit
0ee3f2ab43
1 zmienionych plików z 243 dodań i 150 usunięć
  1. 243 150
      src/views/corporation/deviceModal.vue

+ 243 - 150
src/views/corporation/deviceModal.vue

@@ -16,54 +16,60 @@
           {{ model[field] }}
           {{ model[field] }}
         </template>
         </template>
         <template #subNum="{ model, field }">
         <template #subNum="{ model, field }">
-          <div style="display: flex">
-            <InputNumber v-model:value="model[field]" />
-            <a-button
-              style="margin: 0 20px"
-              @click="changeModal(true)"
-              preIcon="ic:round-add-circle"
-            />
-            <a-button preIcon="ic:round-remove-circle-outline" @click="changeModal(false)" />
-          </div>
+          <!-- {{ model[field] }} -->
+          <input-number
+            v-model:value="model[field]"
+            style="width: 260px; text-align: center"
+            class="justify-center suNum"
+            :min="0"
+            :max="20"
+            @blur="deviceMapping"
+            @press-enter="deviceMapping"
+          >
+            <template #addonBefore>
+              <a-button size="small" type="link" @click="handleMinusDevice">
+                <Icon icon="ic:baseline-minus" :size="20" />
+              </a-button>
+            </template>
+            <template #addonAfter>
+              <a-button size="small" type="link" @click="handlePlusDevice">
+                <Icon icon="ic:round-plus" :size="20" />
+              </a-button>
+            </template>
+          </input-number>
         </template>
         </template>
       </BasicForm>
       </BasicForm>
     </div>
     </div>
   </BasicModal>
   </BasicModal>
 </template>
 </template>
 <script lang="ts">
 <script lang="ts">
-  import { defineComponent, ref, nextTick } from 'vue';
-  import { InputNumber } from 'ant-design-vue';
+  import { defineComponent, ref, nextTick, unref } from 'vue';
   import { BasicModal, useModalInner } from '/@/components/Modal';
   import { BasicModal, useModalInner } from '/@/components/Modal';
   import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
   import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
   import { useMessage } from '/@/hooks/web/useMessage';
   import { useMessage } from '/@/hooks/web/useMessage';
-  import { AddDevice, checkDevice } from '/@/api/corporation/modal';
+  import { InputNumber } from 'ant-design-vue';
+  // AddDevice
+  import { checkDevice } from '/@/api/corporation/modal';
   import { useI18n } from '/@/hooks/web/useI18n';
   import { useI18n } from '/@/hooks/web/useI18n';
+  import { Icon } from '/@/components/Icon/index';
+  import { clamp, range } from 'lodash-es';
+
   export default defineComponent({
   export default defineComponent({
-    components: { BasicModal, BasicForm, InputNumber },
+    components: { BasicModal, BasicForm, InputNumber, Icon },
     props: {
     props: {
       userData: { type: Object },
       userData: { type: Object },
     },
     },
     emits: ['register'],
     emits: ['register'],
     setup(props) {
     setup(props) {
       const modelRef = ref({
       const modelRef = ref({
-        subNum: 0,
-        id: '',
-        userName: '',
+        mappingLength: 0,
       });
       });
-      const num = ref(0);
+
+      // const num = ref(0);
       const { t } = useI18n();
       const { t } = useI18n();
       const { createMessage } = useMessage();
       const { createMessage } = useMessage();
       const { success, error } = createMessage;
       const { success, error } = createMessage;
-      // const debounce = (fn, delay) => {
-      //   var timer = null;
-      //   return function () {
-      //     var context = this, args = arguments;
-      //     clearTimeout(timer);
-      //     timer = setTimeout(function () {
-      //       fn.apply(context, args);
-      //     }, delay);
-      //   };
-      // }
+
       const [register, { closeModal }] = useModalInner((data) => {
       const [register, { closeModal }] = useModalInner((data) => {
         data && onDataReceive(data);
         data && onDataReceive(data);
       });
       });
@@ -102,18 +108,22 @@
         {
         {
           field: 'subNum',
           field: 'subNum',
           component: 'InputNumber',
           component: 'InputNumber',
-          slot: 'subNum',
           label: t('routes.corporation.cameraNum'),
           label: t('routes.corporation.cameraNum'),
+          slot: 'subNum',
+
           colProps: {
           colProps: {
             span: 8,
             span: 8,
           },
           },
-          componentProps: () => {
-            return {
-              // xxxx props schema, tableAction, formModel  checkDevice
-              min: 0,
-              onChange: numOnChange,
-            };
-          },
+          helpMessage: '最多批量增加20个!',
+          // componentProps: () => {
+          //   return {
+          //     // xxxx props schema, tableAction, formModel  checkDevice
+          //     min: 0,
+          //     max: 10,
+          //     // onChange: numOnChange,
+          //     onblur: deviceMapping,
+          //   };
+          // },
         },
         },
       ];
       ];
       // let schemasList = []
       // let schemasList = []
@@ -123,7 +133,7 @@
           setFieldsValue,
           setFieldsValue,
           resetFields,
           resetFields,
           getFieldsValue,
           getFieldsValue,
-          validateFields,
+          validate,
           appendSchemaByField,
           appendSchemaByField,
           removeSchemaByFiled,
           removeSchemaByFiled,
         },
         },
@@ -135,55 +145,58 @@
           span: 24,
           span: 24,
         },
         },
       });
       });
-      function changeModal(type) {
-        let { subNum } = getFieldsValue();
-        if (type) {
-          subNum = subNum + 1;
-        } else if (subNum !== 0) {
-          subNum = subNum - 1;
-        }
-        console.log('schemasList增 ', subNum);
-        setFieldsValue({
-          subNum,
-        });
-        numOnChange(subNum);
-      }
+
+      // async function submitModal() {
+      //   let formData = {
+      //     ...getFieldsValue(),
+      //   };
+      //   let validate = false;
+      //   try {
+      //     const res = await validateFields();
+      //     validate = true;
+      //     console.log('passing', res, formData);
+      //   } catch (error: unknown) {
+      //     console.log('not passing', error);
+      //   }
+      //   if (validate) {
+      //     const { subNum, id, userName } = modelRef.value;
+      //     let childNameList = [];
+      //     Object.keys(formData).map((ele) => {
+      //       if (ele.includes('ID')) {
+      //         childNameList.push(formData[ele]);
+      //       }
+      //     });
+      //     console.log('modelRef.value', Object.keys(formData), childNameList);
+      //     try {
+      //       const res = await AddDevice({
+      //         childNames: childNameList as any as string[],
+      //         companyId: id,
+      //         subNum: String(subNum),
+      //         userName,
+      //       });
+      //       success(res);
+      //       closeModal();
+      //     } catch (errors) {
+      //       // error('errors');
+      //       // console.log('not passing', error);
+      //     }
+      //   }
+      // }
       async function submitModal() {
       async function submitModal() {
-        let formData = {
-          ...getFieldsValue(),
-        };
-        let validate = false;
         try {
         try {
-          const res = await validateFields();
-          validate = true;
-          console.log('passing', res, formData);
-        } catch (error: unknown) {
-          console.log('not passing', error);
-        }
-        if (validate) {
-          const { subNum, id, userName } = modelRef.value;
-          let childNameList = [];
-          Object.keys(formData).map((ele) => {
-            if (ele.includes('ID')) {
-              childNameList.push(formData[ele]);
-            }
-          });
-          console.log('modelRef.value', Object.keys(formData), childNameList);
-          try {
-            const res = await AddDevice({
-              childNames: childNameList as any as string[],
-              companyId: id,
-              subNum: String(subNum),
-              userName,
-            });
-            success(res);
-            closeModal();
-          } catch (errors) {
-            // error('errors');
-            // console.log('not passing', error);
-          }
-        }
+          const values = await validate();
+          console.log('values,', values);
+          // await AddDevice({
+          //   childNames: childNameList as any as string[],
+          //   companyId: id,
+          //   subNum: String(subNum),
+          //   userName,
+          // });
+          success('11');
+          closeModal();
+        } catch (error) {}
       }
       }
+
       function onDataReceive(data) {
       function onDataReceive(data) {
         // 方式1;
         // 方式1;
         resetFields();
         resetFields();
@@ -191,96 +204,176 @@
           ...data.record,
           ...data.record,
           subNum: 0,
           subNum: 0,
         });
         });
+      }
 
 
-        // // 方式2
-        modelRef.value = {
-          ...data.record,
-        };
-        num.value = 0;
-        numOnChange(0);
-        // Reflect.set(modelRef, {
-        //   ...data.record,
-        // });
+      // function numOnChange(data) {
+      //   const value = Number(data);
+      //   if (num.value > value) {
+      //     //减
+      //     let delList = Array.from(new Array(num.value)).map((_, index) => {
+      //       console.log(index, value, num.value);
+      //       if (index >= value) {
+      //         return `ID${index}`;
+      //       }
+      //     });
+
+      //     removeSchemaByFiled(delList as any as string[]);
+      //     console.log('schemasList减', value, num.value, delList);
+      //     // value,num.value,schemasList.filter((_,index) => {return !(index<num.value)}).map((_,index) => `ID${index}`))
+      //   } else {
+      //     //增
+      //     let device = t('routes.corporation.device');
+      //     let schemasList: FormSchema[] = Array.from(new Array(value)).map((_, index) => {
+      //       return {
+      //         field: `ID${index}`,
+      //         component: 'Input',
+      //         label: device + 'ID' + index,
+      //         helpMessage: [t('common.checkTips'), `${device} ${t('common.unusual')}`],
+      //         itemProps: {
+      //           validateTrigger: 'blur',
+      //         },
+      //         colProps: {
+      //           span: 24,
+      //         },
+      //         rules: [
+      //           {
+      //             required: true,
+      //             message: `${t('common.inputText')} ${device} ID`,
+      //           },
+      //           {
+      //             validator: handlevalidator,
+      //           },
+      //         ],
+      //       };
+      //     });
+      //     console.log(
+      //       'schemasList增',
+      //       num.value,
+      //       schemasList.filter((_, index) => {
+      //         return index >= num.value;
+      //       }),
+      //     );
+      //     schemasList
+      //       .filter((_, index) => {
+      //         return index >= num.value;
+      //       })
+      //       .forEach((item) => appendSchemaByField(item, ''));
+      //   }
+      //   num.value = value;
+      // }
+
+      function handleVisibleChange(v) {
+        v && props.userData && nextTick(() => onDataReceive(props.userData));
+      }
 
 
-        // setProps({
-        //   ...data.record,
-        // });
+      async function handleCloseModal() {
+        // numOnChange(0);
+        await setFieldsValue({
+          subNum: 0,
+        });
+        deviceMapping();
       }
       }
-      function numOnChange(data) {
-        const value = Number(data);
-        if (num.value > value) {
-          //减
-          let delList = Array.from(new Array(num.value)).map((_, index) => {
-            console.log(index, value, num.value);
-            if (index >= value) {
-              return `ID${index}`;
-            }
-          });
 
 
-          removeSchemaByFiled(delList as any as string[]);
-          console.log('schemasList减', value, num.value, delList);
-          // value,num.value,schemasList.filter((_,index) => {return !(index<num.value)}).map((_,index) => `ID${index}`))
-        } else {
-          //增
-          let device = t('routes.corporation.device');
-          let schemasList: FormSchema[] = Array.from(new Array(value)).map((_, index) => {
-            return {
-              field: `ID${index}`,
-              component: 'Input',
-              label: device + 'ID' + index,
-              helpMessage: [t('common.checkTips'), `${device} ${t('common.unusual')}`],
-              itemProps: {
-                validateTrigger: 'blur',
+      function setMappingDevice(devices: number, start = 0): FormSchema[] {
+        return Array.from(new Array(devices)).map((_, index) => {
+          const startIndex = start + index + 1;
+          return {
+            field: `ID${startIndex}`,
+            component: 'Input',
+            label: `${t('routes.corporation.device')} ID  ${startIndex}`,
+            helpMessage: [
+              t('common.checkTips'),
+              `${t('routes.corporation.device')} ${t('common.unusual')}`,
+            ],
+            itemProps: {
+              validateTrigger: 'blur',
+            },
+            colProps: {
+              span: 24,
+            },
+            rules: [
+              {
+                required: true,
+                message: `${t('common.inputText')} ${t('routes.corporation.device')} ID`,
               },
               },
-              colProps: {
-                span: 24,
+              {
+                validator: handlevalidator,
               },
               },
-              rules: [
-                {
-                  required: true,
-                  message: `${t('common.inputText')} ${device} ID`,
-                },
-                {
-                  validator: handlevalidator,
-                },
-              ],
-            };
+            ],
+          };
+        });
+      }
+
+      async function deviceMapping() {
+        const values = getFieldsValue();
+        const devices: number = clamp(values.subNum, 0, 20);
+        const currentLength = unref(modelRef).mappingLength;
+
+        const rest = devices - currentLength;
+        if (rest > 0) {
+          //plus
+          const schemas = setMappingDevice(rest, currentLength);
+          console.log('schemas', schemas);
+          const patchs = schemas.map((i: FormSchema) => {
+            return appendSchemaByField(i, '');
+          });
+          await Promise.all(patchs);
+          unref(modelRef).mappingLength = devices;
+          console.log('patch in');
+        } else {
+          // minus
+          const startIndex = currentLength + rest;
+          console.log('rest', rest);
+          console.log('currentLength', currentLength);
+          console.log('startIndex', startIndex);
+          const ranges = range(startIndex + 1, currentLength + 1, 1).map((i) => {
+            return `ID${i}`;
           });
           });
-          console.log(
-            'schemasList增',
-            num.value,
-            schemasList.filter((_, index) => {
-              return index >= num.value;
-            }),
-          );
-          schemasList
-            .filter((_, index) => {
-              return index >= num.value;
-            })
-            .forEach((item) => appendSchemaByField(item, ''));
+          console.log('ranges', ranges);
+          removeSchemaByFiled(ranges);
+          unref(modelRef).mappingLength = devices;
         }
         }
-        num.value = value;
       }
       }
-      function handleVisibleChange(v) {
-        v && props.userData && nextTick(() => onDataReceive(props.userData));
+      async function handlePlusDevice() {
+        const values = getFieldsValue();
+        const currentsubNum = values.subNum;
+        const currentDevice = clamp(currentsubNum + 1, 0, 20);
+        await setFieldsValue({
+          subNum: currentDevice,
+        });
+        deviceMapping();
       }
       }
-      function handleCloseModal() {
-        numOnChange(0);
+      async function handleMinusDevice() {
+        const values = getFieldsValue();
+        const currentsubNum = values.subNum;
+        const currentDevice = clamp(currentsubNum - 1, 0, 20);
+        await setFieldsValue({
+          subNum: currentDevice,
+        });
+        deviceMapping();
       }
       }
+
       return {
       return {
         register,
         register,
         submitModal,
         submitModal,
         schemas,
         schemas,
         registerForm,
         registerForm,
-        numOnChange,
+        // numOnChange,
         modelRef,
         modelRef,
         handleVisibleChange,
         handleVisibleChange,
-        num,
+        // num,
         errorMsg: error,
         errorMsg: error,
         handleCloseModal,
         handleCloseModal,
+        deviceMapping,
         t,
         t,
-        changeModal,
+        handlePlusDevice,
+        handleMinusDevice,
       };
       };
     },
     },
   });
   });
 </script>
 </script>
+<style lang="less">
+  .suNum .ant-input-number-input {
+    text-align: center;
+  }
+</style>