vue + element-ui el-form在el-table中的表单验证

在开发过程中偶尔遇到el-table嵌套el-form,而且还需要表单验证的需求,如下图:
vue + element-ui el-form在el-table中的表单验证_第1张图片

解决方案:

动态定义el-form-item的prop属性,保证唯一性,并设置独立的rules属性。

<el-form-item :prop="'applyDataList.' + scope.$index + '.value3'" :rules="applyRules.value3">

html代码:

<el-form ref="applyForm" :model="applyForm" :rules="applyRules">
 <el-table
   :data="applyForm.applyDataList"
   border
   stripe>
   <el-table-column label="*模拟充值">
     <template slot-scope="scope">
       <el-form-item :prop="'applyDataList.' + scope.$index + '.value3'" :rules="applyRules.value3">
         <el-select v-model="scope.row.value3" placeholder="请选择模拟充值">
           <el-option label="充值1" value="1"/>
           <el-option label="充值2" value="2"/>
         </el-select>
       </el-form-item>
     </template>
   </el-table-column>

   <el-table-column label="*申请数量">
     <template slot-scope="scope">
       <el-form-item :prop="'applyDataList.' + scope.$index + '.value4'" :rules="applyRules.value4">
         <el-input v-model="scope.row.value4" placeholder="请输入申请数量"/>
       </el-form-item>
     </template>
   </el-table-column>
  
   <el-table-column label="消耗">
     <template slot-scope="scope">
       <span>{{ scope.row.value6 }}</span>
     </template>
   </el-table-column>
   
   <el-table-column label="操作" width="100px;">
     <template slot-scope="scope">
       <el-button type="text" @click="delBtn(scope.$index)">删除</el-button>
     </template>
   </el-table-column>
 </el-table>
</el-form>

js代码:

data() {
  return {
    applyForm: {
      applyDataList: []
    },
    applyRules: {
      value3: [{ required: true, message: '请选择模拟充值', trigger: 'change' }],
      value4: [{ required: true, message: '请输入申请数量', trigger: 'change' }]
    }
  }
},
methods: {
  // 提交表单
  saveEditBtn() {
    this.$refs.applyForm.validate((valid) => {
      if (!valid) {
        return false
      }
      // TODO:
    })
  }
}

你可能感兴趣的:(Vue,web前端)