在 Element UI 的 el-table 行编辑模式下,el-form 无法直接校验输入框的值,因为行编辑模式会将输入框的值绑定到行数据的属性中,而不是直接绑定到表单数据中。

为了解决这个问题,需要手动触发 el-form 的校验方法。在 el-table 的 @edit-start@edit-end 事件中,调用 el-form 的 validate 方法即可。

示例代码如下:

<el-table :data="tableData" @edit-start="onEditStart" @edit-end="onEditEnd">
  <el-table-column prop="name" label="姓名">
    <template slot-scope="scope">
      <el-form-item :prop="'tableData.' + scope.$index + '.name'" :rules="[ { required: true, message: '请输入姓名' } ]">
        <el-input v-model="scope.row.name" />
      </el-form-item>
    </template>
  </el-table-column>
  <el-table-column prop="age" label="年龄">
    <template slot-scope="scope">
      <el-form-item :prop="'tableData.' + scope.$index + '.age'" :rules="[ { required: true, message: '请输入年龄' } ]">
        <el-input v-model="scope.row.age" />
      </el-form-item>
    </template>
  </el-table-column>
</el-table>

...

methods: {
  onEditStart() {
    this.$refs.form.validate()
  },
  onEditEnd() {
    this.$refs.form.validate()
  }
}

在上面的示例中,我们使用了 el-form-item 的 prop 属性来指定校验规则和绑定数据。在 onEditStartonEditEnd 事件中,调用 el-form 的 validate 方法触发表单的校验。注意,这里我们需要给 el-form 添加一个 ref 属性,以便在方法中引用。

Element UI: 在 el-table 行编辑模式下如何执行 el-form 校验

原文地址: https://www.cveoy.top/t/topic/oPbk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录