2021-09-08

这篇博客介绍了如何在Vue项目中使用ElementUI组件库来动态渲染表单,并实现Checkbox多选框组的验证。通过后端返回的数据格式,对表单元素进行绑定和验证配置,确保至少选择一项。在提交前进行额外验证,确保符合业务需求。同时,展示了如何处理后端返回的数据,将其转换为适合表单展示的格式。
摘要由CSDN通过智能技术生成

element + vue: 循环渲染表单+Checkbox 多选框组的动态验证

先看效果图(需求)
在这里插入图片描述
后端返回代码格式(主要是根据返回的格式对数据进行一定变形,Checkbox 多选框的v-model必须为数组):
在这里插入图片描述
处理后端返回值:
在这里插入图片描述

<template>
  <div class="functionConfig third">
    <div class="third-formOne">
      <div class="formOne-btn">
        <div class="btn-left">
          <span class="left-back-content">核验设置</span>
        </div>

        <div class="btn-right">
          <el-button
            class="btn-two"
            type="primary"
            @click="preservation('ruleForm')"
            v-el-disabel-repeat-click
            >保存</el-button
          >

          <el-button class="btn-two" type="default" @click="reset"
            >重置</el-button
          >
        </div>
      </div>

      <div class="formOne-forms">
        <el-form
          label-width="46px"
          :model="ruleForm"
          :show-message="false"
          :rules="rules"
          ref="ruleForm"
          @validate="validateOne"
        >
          <div class="forms-one" style="margin-top: 57px">
            <div class="one-title">
              <div class="title-left">
                <span class="left-icon">
                  <i class="el-icon-s-operation"></i>
                </span>

                <span class="left-content">核验要素</span>
              </div>
            </div>

            <div class="one-list list-line">
              <div class="list-one-line">
                <div >
                  <el-form-item
                    v-for="(value,key,index) in ruleForm" :key="index" //这里for in 循环对象
                    :prop="key"
                    :rules="[
                      {
                        type: 'array',
                        required: true,
                        message: `${key}设备至少选择一项`,
                        trigger: 'change',
                      },
                    ]"
                    style="margin: 0"
                  >
                    <div style="display: flex; align-items: center">
                      <span style="width: 160px; text-align: right">
                        <span style="color: #f56c6c; font-size: 12px">*</span> //我没有用表单自带的labe所以没有红色的*号(el-popover的原因,需求需要el-popover和labe在一起)
                        <span style="padding: 0 5px; font-size: 12px" v-if="key==='OneStepFV'">一键核验(OneStepFV)</span>
                        <span style="padding: 0 5px; font-size: 12px" v-else-if="key==='JSAPI'">学生自主核验(JSAPI)</span>
                        <span style="padding: 0 5px; font-size: 12px" v-else>{{key}}</span>
                        <el-popover
                          v-show="key == 'V2' || key == 'OneStepFV' || key == 'FT1_MINI'"
                          style="margin: 0 5px 0 0"
                          placement="top-start"
                          width="300"
                          trigger="hover"
                          content="公安部核验、用户照片需至少勾选一个"
                        >
                          <i
                            slot="reference"
                            class="el-icon-warning-outline"
                          ></i>
                        </el-popover>
                      </span>
                      <el-checkbox-group
                        style="display: inline-block; margin-top: 3px"
                        v-model="ruleForm[key]" //动态绑定
                      >
                        <el-checkbox label="身份信息核验" disabled
                          >身份信息核验</el-checkbox>//身份信息核验这一个选择项目是写死了的,所以我就做了个假的
                        <template v-for="(item,index) in checked1">
                          <el-checkbox  :label="item" :key="index" >{{item}}</el-checkbox>
                        </template>
                      </el-checkbox-group>
                    </div>
                  </el-form-item>
                </div>
              </div>
            </div>
          </div>
          </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "thirdThree",

  data() {
    return {
      ruleForm: {
      },
      countNum: 1,
      checked1: [ "公安部核验", "用户照片"],
      rules: {}
    };
  },

  mounted() {
    this.roleStuList(); //页面初始化加载后端返回数据
  },

  methods: {
    async roleStuList() {
      try {
        let {
          data: { status, msg, result },
        } = await this.$store.dispatch("getSet");

        if (status === 1000) {
          const arr = JSON.parse(JSON.stringify(result))//深拷贝一下返回值
          let NEwobj = {}
          arr.forEach((elment) => {
            const arr = ['身份信息核验']; //Checkbox 多选框对应选项的Labe如果再数组在存在,即为选中
            if (elment.publicSecurityIdentityCheck === "1") { //"1"为选中 "0"为未选中
              arr.push("公安部核验");
            }

            if (elment.userFaceCheck === "1") {
              arr.push("用户照片");
            }
            NEwobj[elment.id] = arr;//给返回值变形
          });
          this.ruleForm = JSON.parse(JSON.stringify(NEwobj))
          console.log(this.ruleForm);
        } else {
          this.$message({
            type: "error",

            message: msg,
          });
        }
      } catch (err) {
        console.log(err);
      }
    },

    validateOne(prop, msgStatus, validateMessage) {
      // console.log(prop, msgStatus, validateMessage)

      if (!msgStatus && !this.countNum) {
        this.countNum += 1; //这句话是为了让错误提示一次只出现一条

        if (validateMessage) {
          this.$message.error(validateMessage);
        }
      }
    },

    async preservation(formName) { //提交前处理获取到的值
      this.countNum = 0;

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.countNumTwo = 1;
          const arr=[]
          for(var element in this.ruleForm){//再这里再对至少选择两项的选择项做验证,上面都做了最低选择一项
            if(element=='OneStepFV' && this.ruleForm[element].length<2 || element=='JSAPI' && this.ruleForm[element].length<2 || element=='FT1_MINI' && this.ruleForm[element].length<2){
              this.$message.error(`${element}设备 公安部核验、用户照片需至少勾选一个`)
              return
            }
            const smallJson={}//应后端要求是对返回参数在做更改
            smallJson.id=element
            if(this.ruleForm[element].indexOf('公安部核验') != -1){
              smallJson.publicSecurityIdentityCheck='1'
            }else{
              smallJson.publicSecurityIdentityCheck='0'
            }
            if(this.ruleForm[element].indexOf('用户照片') != -1){
              smallJson.userFaceCheck='1'
            }else{
              smallJson.userFaceCheck='0'
            }
            arr.push(smallJson)
          }
          console.log(arr)
          this.goUpdate(arr)
        }
      });
    },

    async goUpdate(arr) {
      let parms = {
        options: arr,
      };

      try {
        let {
          data: { status, msg },
        } = await this.$store.dispatch("saveSet", parms);

        if (status == 1000) {
          console.log(msg);
          this.$message({
            message: msg,
            type: "success",
          });
        } else {
          this.$message({
            type: "error",

            message: msg,
          });
        }
      } catch (err) {
        console.log(err);
      }
    },

    reset() {//重置
      this.roleStuList();
    },
  },
};
</script>
<style lang="scss">
.aaa {
  display: inline-block;

  text-align: right;
}
</style>


返回给后端的参数
在这里插入图片描述
就这样完美

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值