表格示例:
该案例在动态表格中,验证同一个字段是否为空,是否超出最大限制字符 ,是否做不重名验证;
示例中主要是验证对应别名(columnComment)字段,
所有对每个别名字段循环一个el-form rules model
对每个循环的 el-form-item中加入 :ref="`elFormItem${scope.$index}`"
<el-table :data="tableFieldList"
class="data-field-table">
<el-table-column prop="columnName"
label="变量名称">
<template slot-scope="scope">
<long-str-cut>{{scope.row.columnName}}</long-str-cut>
</template>
</el-table-column>
<el-table-column prop="columnType"
label="类型">
</el-table-column>
<el-table-column prop="columnComment"
label="对应别名">
<template slot-scope="scope">
<el-form :ref="`tableRow${scope.$index}`"
:model="scope.row"
:rules="rules">
<el-form-item :ref="`elFormItem${scope.$index}`"
prop="columnComment">
<el-input size="small"
v-model.trim="scope.row.columnComment"
placeholder="请输入对应别名" />
</el-form-item>
</el-form>
</template>
</el-table-column>
</el-table>
computed: {
rules() {
return { columnComment: [{ validator: this.validateName, trigger: 'blur' }] }
}
},
validateName(rule, value, callback) {
if (!value) {
return callback(new Error('不能为空!'))
}
if (value.length > 10) {
return callback(new Error('请输入10个及以内的别名字符!'))
}
//检测重名步骤
let index = 0
for (let i = 0; i < this.tableFieldList.length; i++) {
//寻找是否讯在重复别名
if (this.tableFieldList[i].columnComment === value) {
index += 1
if (index > 1) {
return callback(new Error('存在相同的别名!'))
}
}
//首先找出其他error显示框 数据大了会卡死
//如果error 就手动验证一次
//if (this.$refs['elFormItem' + i].validateState === 'error') {
// this.$refs['tableRow' + i].validateField('columnComment')
// }
}
callback()
},
submitForm() {
let success = [];
for (let i = 0; i < this.tableFieldList.length; i++) {
this.$refs['tableRow' + i].validate((valid) => {
if (valid) {
success.push(true)
}
});
}
if (success.length < this.tableFieldList.length) {
this.$message.warning('存在错误别名,请更改!')
} else {
//保存操作
this.addOrSave()
}
},