Element表单嵌套数据验证

2020-10-14 09:43:43 浏览数 (1)

除了在 Form 组件上一次性传递所有的验证规则外还可以在单个的表单域上传递属性的验证规则

假如数据格式如下:

代码语言:javascript复制
      qiantaoForm:{
        name:"",
        age:"20",
        children:[{
          name:"jack1",
          age:"10"
        },{
          name:"jack2",
          age:"12"
        }]
      },
代码语言:javascript复制
    <el-form :model="qiantaoForm" :rules="rules">
      <div>
        <div>主内容</div>
        <el-form-item label="名称" prop="name">
          <el-input v-model="qiantaoForm.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="qiantaoForm.age"></el-input>
        </el-form-item>
      </div>
      <div v-for="(item,index) in qiantaoForm.children" :key="index">
        <div>子内容--{{item.name}}</div>
        <el-form-item label="子名称" :prop="`children.${index}.name`" :rules="rules.name">
          <el-input v-model="item.name"></el-input>
        </el-form-item>
        <el-form-item label="子名称" :prop="`children.${index}.age`">
          <el-input v-model="item.age"></el-input>
        </el-form-item>
      </div>
    </el-form>
代码语言:javascript复制
      rules: {
        name: [{ required: true, message: "输入内容", trigger: "blur" }],
        age: [{ required: true, message: "输入年龄内容", trigger: "blur" }]
      }

注意

子内容的属性为 prop="`children.${index}.name`" 或者 prop= "'children.' index '.value'" 因为el-form中的 :model="qiantaoForm" 是最外层结构

0 人点赞