vue 根据动态生成的form表单的整体的数据回显,赋值及校验和提交

主要负责处理表单数据的展示、编辑和提交,以及与后端接口的交互。(处理选择地址、处理单选框选中、设置表单验证、提交表单、校验文件是否上传完成、处理上传文件等)

  • 公共调用方法mixins文件
import HCommonPop from "@/components/commonPop/index";
import HCommonFormItem from "@/components/commonFormItem/index";
import { getSelectList } from "@/api/initProject";

export default {
  data() {
    return {
      oldFormList: [],
      detailInfo: "",
      axiosInfo: {}
    };
  },
  components: {
    HCommonPop,
    HCommonFormItem
  },
 
  methods: {
    handleSelectAddress(val, label, row, level) {
      this.formList = this.handleFindDataSetVal(this.formList, row.field, val);
    },
    handleCheckedRadio(val, row) {
      this.formList = this.handleFindDataSetVal(this.formList, row.field, val);
    },
    handleSetFormValidate(treeList, fieldVal, val, keyList = []) {
      if (!treeList || !treeList.length) {
        return;
      }
      treeList.forEach((item) => {
        const formValidate = item.formValidate;
        for (let key in formValidate) {
          if (keyList.length > 0 ? keyList.includes(key) : key === fieldVal) {
            formValidate[key][0].required = val;
          }
        }
        this.handleSetFormValidate(item.children, fieldVal, val, keyList);
      });
      return treeList;
    },
    handleSetSubmitData(treeList, dataList) {
      if (!treeList || !treeList.length) {
        return [];
      }
      treeList.forEach((item) => {
        if (item.purchasingInformation && JSON.stringify(item.purchasingInformation) !== "{}" && (item.display === undefined || item.display === true)) {
          const updateObj = {};
          item.purchasingInformation.formLabel.forEach((label) => {
            const field = label.field;
            const formValue = item.purchasingInformation.form[field];
            if (label.type === "check") {
              updateObj[field] = Array.isArray(formValue) ? formValue.join(",") : formValue;
            } else if (label.type === "examine") {
              delete item.purchasingInformation.form[field];
            } else if (label.type === "upload") {
              updateObj[field] = typeof formValue === "object" ? JSON.stringify(formValue) : formValue;
            } else if (label.type === "textarea" && label.dataType === "multiple") {
              const textareaData = JSON.parse(JSON.stringify(formValue));
              const textareaFilterData = textareaData.filter((el) => el.value !== "");
              if (textareaFilterData.length > 0) {
                textareaFilterData.forEach((el) => {
                  if (!el.disabled) {
                    el.disabled = true;
                    el.userName = this.userInfo.nickName;
                    el.date = new Date().format("yyyy-MM-dd hh:mm:ss");
                    el.value = `${el.date} ${el.userName}: ${el.value}`;
                  }
                });
              }
              updateObj[field] = textareaFilterData.length > 0 ? JSON.stringify(textareaFilterData) : "";
            } else if (label.display) {
              updateObj[field] = formValue;
            }
          });
          dataList.push(updateObj);
        }
        if (item.children) {
          this.handleSetSubmitData(item.children, dataList);
        }
      });
      return dataList;
    },
    // 寻找某个属性值
    handleFindDataInForm(treeList, field, myInfo, paramVal = "value") {
      if (!treeList || !treeList.length) {
        return myInfo;
      }
      for (const node of treeList) {
        const { purchasingInformation, children } = node;

        if (
          purchasingInformation &&
          purchasingInformation.form.hasOwnProperty(field)
        ) {
          const { formLabel } = purchasingInformation;
          const matchingField = formLabel.find(label => label.field === field);

          if (matchingField) {
            myInfo[paramVal] =
              paramVal === "options"
                ? matchingField.options
                : purchasingInformation.form[field];

            return myInfo;
          }
        }

        this.handleFindDataInForm(children, field, myInfo, paramVal);
      }
      return myInfo;
    },
    handleChangeFormKeyVal() {},
    // 为某个属性赋值
    handleFindDataSetVal(treeList, field, val) {
      if (!treeList || !treeList.length) {
        return;
      }
      treeList.forEach((item) => {
        const purchasingInformation = item.purchasingInformation;
        if (
            purchasingInformation &&
            (item.display === undefined || item.display === true) &&
            purchasingInformation.form[field] !== undefined
        ) {
          const formLabel = purchasingInformation.formLabel;
          const targetLabel = formLabel.find((label) => label.field === field);
          if (targetLabel) {
            purchasingInformation.form[field] = val;
          }
          return;
        }
        this.handleFindDataSetVal(item.children, field, val);
      });
      return treeList;
    },
    submit() {
      this.$commonMessage.confrimMessage(
        { message: "是否保存?", type: "success" },
        () => {
          let myForm = {
            imgData: [],
            list: []
          };
          let imgStatus = this.handleCheckImgAndTable(
            this.formList,
            myForm,
            "img"
          );
          if (imgStatus.imgData.length > 0) {
            this.$commonMessage.message({
              type: "warning",
              message: "文件上传中,请稍后!"
            });
            return;
          }
          this.handleSetAxiosData();
        }
      );
    },
    //校验文件是否上传完成
    handleCheckImgAndTable(treeList, myForm, operatorType) {
      if (!treeList || !treeList.length) {
        return;
      }
      treeList.forEach((item) => {
        const purchasingInformation = item.purchasingInformation;
        if (purchasingInformation && JSON.stringify(purchasingInformation) !== "{}") {
          purchasingInformation.formLabel.forEach((label) => {
            if (operatorType === "img" && label.type === "upload") {
              const uploadImgList = label.uploadImgList;
              if (uploadImgList.some((el) => !el.isUpload)) {
                myForm.imgData.push(1);
              } else {
                const chooseImgListOrigin = label.chooseImgListOrigin;
                const imgList = chooseImgListOrigin.map((item) => item.new || item);
                purchasingInformation.form[label.field] = imgList.length > 0 ? JSON.stringify(imgList) : "";
              }
            }
          });
        }
        if (item.children) {
          this.handleCheckImgAndTable(item.children, myForm, operatorType);
        }
      });
      if (operatorType === "img") {
        myForm.list = treeList;
      }
      return myForm;
    },
    handleCheckUpload(treeList, fieldInfo, fileList) {
      if (!treeList || !treeList.length) {
        return;
      }
      treeList.forEach((item) => {
        if (item.$children && item.$children.length > 0 && !item.$refs.rulesForm) {
          this.handleCheckUpload(item.$children, fieldInfo, fileList);
        } else {
          if (fileList.length > 0) {
            const formRules = item.$refs.rulesForm?item.$refs.rulesForm.rules:{};
            formRules&&formRules[fieldInfo.field] && item.$refs.rulesForm.clearValidate(fieldInfo.field);
          }
        }
      });
    },
    handleSelectChange() {},
    //上传文件的处理(删除及添加)
    handleImgInfo(val, file, info) {
      this.formList = this.handleSetImgVal(this.formList, val, file, info);
    },
    //上传文件的处理(删除及添加)
    handleImgLoad(val, formInfo) {
      this.formList = this.handleSetImgVal(this.formList, val, "add", formInfo);
    },
    //上传文件的处理(删除及添加)
    handleSetImgVal(treeList, val, file, formInfo) {
      if (!treeList || !treeList.length) {
        return;
      }
      const node = treeList.find(
          (item) =>
              item.purchasingInformation &&
              item.purchasingInformation.form[formInfo.field] !== undefined
      );
      if (node) {
        for (let j = 0; j < node.purchasingInformation.formLabel.length; j++) {
          if (
              node.purchasingInformation.formLabel[j].field == formInfo.field
          ) {
            const chooseImgListOrigin =
                node.purchasingInformation.formLabel[j].chooseImgListOrigin;
            if (file == "delete") {
              const index = chooseImgListOrigin.findIndex(
                  (ele) => ele.id === val.id || ele.uid === val.uid
              );
              chooseImgListOrigin.splice(index, 1);
            } else if (file == "add") {
              this.$set(
                  node.purchasingInformation.formLabel[j],
                  "uploadImgList",
                  val
              );
            } else {
              chooseImgListOrigin.push({
                new: val,
                old: file,
              });
              this.handleCheckUpload(this.$refs.myFromItem.$children, formInfo, chooseImgListOrigin);
            }
            break;
          }
        }
      } else {
        treeList.forEach((item) => {
          this.handleSetImgVal(item.children, val, file, formInfo);
        });
      }
      return treeList;
    },
    // 获取所有表单填写的form
    handleGetFormData(formList) {
      let dataList = [];
      let submitData = this.handleSetSubmitData(
        JSON.parse(JSON.stringify(this[formList])),
        dataList
      );

      let submitObj = {};
      submitData.forEach(el => {
        submitObj = {
          ...submitObj,
          ...el
        };
      });
      return submitObj;
    },

    handleCheckTreeFormValidate(treeList, myValidate) {
      if (!treeList || !treeList.length) {
        return;
      }
      treeList.forEach((item) => {
        if (item && item.$children && item.$children.length > 0 && item.$refs && !item.$refs.rulesForm) {
          this.handleCheckTreeFormValidate(item.$children, myValidate);
        } else if (item && item.$refs && item.$refs.rulesForm) {
          myValidate.push(
              new Promise((resolve, reject) => {
                item.$refs.rulesForm.validate((valid, validObj) => {
                  if (valid) {
                    resolve();
                  } else {
                    console.log(valid, validObj, "valid, validObj");
                    reject();
                  }
                });
              })
          );
        }
      });
      return myValidate;
    },
    handleSetAxiosData(submitType, type) {
      let submitObj = this.handleGetFormData("formList");
      let validate = [];
      let validateList = [];
      if (
        this.detailInfo.type == "edit" &&
        this.detailInfo.page == "warehouse"
      ) {
        this.handleSubmitData(submitObj, type);
        return;
      }
      if (
        this.$refs.myFromItem.$children &&
        this.$refs.myFromItem.$children.length > 0
      ) {
        validateList = this.handleCheckTreeFormValidate(
          this.$refs.myFromItem.$children,
          validate
        );
      }
      console.log(validateList, "validateList");
      Promise.all(validateList)
        .then(() => {
          let ruleFlag = false;
          if (this.$route.name == "AddRules") {
            let ruleFlagMsg = this.handleValidateUp();
            if (ruleFlagMsg) {
              this.$commonMessage.message({
                type: "warning",
                message: `${ruleFlagMsg}`
              });
              ruleFlag = true;
            }
          }
          if (!ruleFlag && type != "examine") {
            this.handleSubmitData(submitObj, type);
          }
          if (type == "examine") {
            this.handleOperatorExamine(submitType, submitObj);
          }
        })
        .catch(() => {
          this.$commonMessage.message({
            type: "warning",
            message: `请完善信息并检查填写信息是否符合要求!`
          });
        });
    },
    // 数据回显
    handleUpdateForm(treeList, list, info) {
      if (!treeList || treeList.length === 0) {
        return;
      }

      for (const item of treeList) {
        const {purchasingInformation, display} = item;

        if (purchasingInformation && Object.keys(purchasingInformation).length !== 0 && (display === undefined || display === true)) {
          for (const formLabel of purchasingInformation.formLabel) {
            const {field, type, dataType, disabled} = formLabel;
            let key = field;
            let infoVal = "";

            if (type === "upload") {
              infoVal = info &&info[key] ? JSON.parse(info[key]) : this.axiosInfo[key] ? JSON.parse( this.axiosInfo[key]):'';
              item.purchasingInformation.form[key] = infoVal;
              if(infoVal) {
                formLabel.chooseImgListOrigin = JSON.parse(JSON.stringify(infoVal));
                formLabel.fileList = JSON.parse(JSON.stringify(infoVal));
              }


              if (disabled) {
                formLabel.initData = infoVal ? JSON.stringify(infoVal) : "";
              }
            } else if (type === "textarea" && dataType === "multiple") {
              let inputValue = "";

              if (this.axiosInfo[key] && this.commonFunc.judgeIsArray(this.axiosInfo[key])) {
                const textareaValues = JSON.parse(this.axiosInfo[key]);
                const textareaValue = [{
                  disabled: true,
                  date: "",
                  userName: "",
                  value: ""
                }];

                for (let v = 0; v < textareaValues.length; v++) {
                  textareaValue[0].value += textareaValues[v].value + (textareaValues.length - 1 === v ? "" : "\n");
                }

                inputValue = textareaValue;
              } else {
                inputValue = this.axiosInfo[key]
                    ? [{
                      date: "",
                      userName: "",
                      disabled: true,
                      value: this.axiosInfo[key]
                    }]
                    : [{
                      date: "",
                      userName: "",
                      disabled: false,
                      value: ""
                    }];
              }

              formLabel.deleteWord = inputValue;
              item.purchasingInformation.form[key] = inputValue;
            } else {
              item.purchasingInformation.form[key] = this.axiosInfo[key] !== undefined && this.axiosInfo[key] !== null && this.axiosInfo[key] !== ""
                  ? this.axiosInfo[key]
                  : item.purchasingInformation.form[key] !== undefined && item.purchasingInformation.form[key] !== "" && item.purchasingInformation.form[key] !== null
                      ? item.purchasingInformation.form[key]
                      : "";
            }
          }
        }

        if (item.children) {
          this.handleUpdateForm(item.children, list, info);
        }
      }

      return treeList;
    },
    // 判断是否需要调用接口显示下拉信息
    handleSetValForFormSelect(treeList, fieldVal, index) {
      if (!treeList || !treeList.length) {
        return;
      }
      for (let i = 0; i < treeList.length; i++) {
        if (
          treeList[i].purchasingInformation &&
          JSON.stringify(treeList[i].purchasingInformation) != "{}"
        ) {
          for (
            let k = 0;
            k < treeList[i].purchasingInformation.formLabel.length;
            k++
          ) {
            if (treeList[i].purchasingInformation.formLabel[k].selectUrl) {
              this.handleGetSelectList(
                treeList[i].purchasingInformation.formLabel[k].selectUrl,
                treeList[i].purchasingInformation.formLabel[k],
                fieldVal,
                index
              );
            }
            if (
              treeList[i].purchasingInformation.formLabel[k].type == "examine"
            ) {
              this.handleGetFlowTask(
                treeList[i].purchasingInformation.formLabel[k],
                fieldVal,
                index
              );
            }
          }
        }
        if (treeList[i].children) {
          this.handleSetValForFormSelect(treeList[i].children, fieldVal, index);
        }
      }
    },
    // 获取form中select的下拉选
    async handleGetSelectList(url, obj, fieldVal, index, params) {
      let result = await getSelectList(url, params);
      this[fieldVal] = this.handleSetValForSelect(
        this[fieldVal],
        result,
        obj,
        "normal"
      );
      if (this.$route.name == "AddRules") {
        if (JSON.stringify(this.axiosInfo) != "{}") {
          this.handleSelectChange(this.axiosInfo.standardCode, "standardCode");
          this.handleSelectChange(this.axiosInfo.checkType, "checkType");
        }
      }
    },

    // 审核人下拉
    async handleGetFlowTask(obj, fieldVal, index) {
      if (this.isMineExamine) {
        await this.handleGetExamineInfo(obj, fieldVal, index);
      } else {
      }
    },

    // form中下拉赋值
    handleSetValForSelect(treeList, data, obj, index) {
      if (!treeList || !treeList.length) {
        return treeList;
      }

      for (let i = 0; i < treeList.length; i++) {
        const purchasingInfo = treeList[i].purchasingInformation;

        if (purchasingInfo && purchasingInfo.form[obj.field] !== undefined) {
          const formLabel = purchasingInfo.formLabel.find(
              (label) => label.field === obj.field
          );

          if (formLabel) {
            const target = index !== "normal"
                ? formLabel.tableColumns[index]
                : formLabel;

            this.$set(target, "options", data);
          }
        }

        this.handleSetValForSelect(treeList[i].children, data, obj, index);
      }

      return treeList;
    },
    handleSetFormDisabled(
      treeList,
      type,
      fieldListWidthFit = [],
      fieldVal = "type",
      param = "selectUrl",
      paramVal = "/core/select/crm-dealer-type"
    ) {
      if (!treeList || !treeList.length) {
        return;
      }
      for (let i = 0; i < treeList.length; i++) {
        const purchasingInformation = treeList[i].purchasingInformation;

        for (let j = 0; j < purchasingInformation.formLabel.length; j++) {
          if (type == "special") {
            if (fieldVal == purchasingInformation.formLabel[j].field) {
              this.$set(purchasingInformation.formLabel[j], param, paramVal);
            }
          } else {
            if (type != "disabled") {
              this.$set(purchasingInformation.formLabel[j], "disabled", true);
            }
            if (
              fieldListWidthFit.includes(
                purchasingInformation.formLabel[j].field
              )
            ) {
              if (type == "disabled") {
                this.$set(purchasingInformation.formLabel[j], "disabled", true);
              } else {
                this.$set(purchasingInformation.formLabel[j], "widthFit", true);
              }
            }
            if (fieldVal == purchasingInformation.formLabel[j].field) {
              this.$set(purchasingInformation.formLabel[j], "param", "");
            }
          }
        }

        this.handleSetFormDisabled(treeList[i].children);
      }
      return treeList;
    },

    handleGetDataToForm() {
      // 数据回显赋值
      this.formList = this.handleUpdateForm(this.formList);
    },
    handleBackMessage() {
      this.$commonMessage.confrimMessage(
        { message: "有部分修改尚未保存,确定要离开该页面吗?", type: "success" },
        () => {
          this.handleBack();
        }
      );
    },
    back() {
      console.log("back");
      let formList = JSON.stringify(this.handleGetFormData("formList"));

      if (this.oldFormList == formList || this.detailInfo.type == "detail") {
        this.handleBack();

        return;
      }
      this.handleBackMessage();
    },
    handleBack() {
      this.$router.back();
    }
  },
  mounted() {
    // 下拉选赋值
    this.handleSetValForFormSelect(this.formList, "formList");
    this.$nextTick(() => {
      this.oldFormList = JSON.stringify(this.handleGetFormData("formList"));
    });
  },
  destroyed() {},
  created() {
    if (!this.isDialog) {
      this.$store.commit("setBoxBgVisible", false);
      this.detailInfo = this.$route.query.detailInfo
        ? window.atob(this.$route.query.detailInfo)
          ? JSON.parse(
              decodeURIComponent(window.atob(this.$route.query.detailInfo))
            )
          : {}
        : "";
      this.title = this.detailInfo.title;
    }
  }
};

  • 在vue文件中获取到详情数据回显



你可能感兴趣的:(vue.js,javascript,前端)