Element UI el-table 中 children 的 input 无法进行 el-form 校验的解决方法
如果你想在 el-table 中使用 el-form 校验,可以使用以下方法:
- 在 el-table 的列定义中,使用 scoped slot 来自定义每个单元格的内容,将 input 组件放在其中,并将 v-model 绑定到数据源中的相应属性:
<template>
<el-table :data="tableData">
<el-table-column label="Username">
<template slot-scope="scope">
<el-form-item prop='username'>
<el-input v-model="scope.row.username"></el-input>
</el-form-item>
</template>
</el-table-column>
<el-table-column label="Email">
<template slot-scope="scope">
<el-form-item prop='email'>
<el-input v-model="scope.row.email"></el-input>
</el-form-item>
</template>
</el-table-column>
</el-table>
</template>
- 在 el-form 中使用 ref 属性给表格命名,并在提交时调用该表格的 validate 方法进行校验:
<template>
<el-form :model="form" ref="myTable">
<el-table :data="tableData">
...
</el-table>
<el-button @click="submitForm">Submit</el-button>
</el-form>
</template>
<script>
export default {
methods: {
submitForm() {
this.$refs.myTable.validate((valid) => {
if (valid) {
// 校验通过,提交表单
} else {
// 校验失败,处理错误
}
});
},
},
}
</script>
- 在 el-form-item 中使用 prop 属性来指定要校验的字段名,该名称应与数据源中的属性名称相同。如果 prop 属性值不匹配,将无法进行校验。
注意:在使用 el-table 时,需要确保给表格传递一个唯一的 key 属性,以便在数据更新时正确地渲染和更新表格。
原文地址: https://www.cveoy.top/t/topic/oPbu 著作权归作者所有。请勿转载和采集!