element的表单组件自带的校验方法是非常方便的,API也非常全,不过有一点则是如果el-form组件上没有绑定mode,校验对应的一些方法(如:validate)就会用不了,所以用了以下方式
element表单没有绑定mode时进行校验问题
<template>
<div>
<el-form ref="formRef" :model="form" :rules="tableRules" label-width="130px" inline>
</el-form>
<el-form :rules="tableRules" ref="tableFormRef">
<el-table
style="width: 600px"
:data="portCfgList"
>
<el-table-column
label="编号"
align="center"
prop="portId"
class-name="table-bg-class"
>
<template slot-scope="scope">
{{ scope.row.portId }}
</template>
</el-table-column>
<el-table-column
label="主ip"
align="center"
prop="ipAddress"
class-name="table-bg-class"
>
<template slot-scope="scope">
<el-form-item
:prop="`portCfgList.${scope.$index}.ipAddress`"
:rules="tableRules.ipAddress"
>
<el-input
v-model="scope.row.ipAddress"
placeholder="请输入"
maxlength="15"
/>
</el-form-item>
</template>
</el-table-column>
<el-table-column
label="备ip"
align="center"
prop="gateway"
class-name="table-bg-class"
>
<template slot-scope="scope">
<el-form-item
:prop="`portCfgList.${scope.$index}.gateway`"
:rules="tableRules.gateway"
>
<el-input
v-model="scope.row.gateway"
placeholder="请输入"
maxlength="15"
/>
</el-form-item>
</template>
</el-table-column>
</el-table>
</el-form>
<el-button type="primary" @click="submitForm">确 定</el-button>
</div>
</template>
<script>
export default {
data() {
const regexIP =
/^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.((1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/; //ip校验总长15位
const vip = (rule, value, callback) => {
let index = rule.field.split(".")[1];
let val = rule.field.split(".")[2];
let stats = this.portCfgList[index][val];
// 此时的业务场景是表格中的并非必穿,但是填写了就必须写对
if (!stats) {
callback();
return;
}
if (regexIP.test(stats)) {
callback();
return;
} else {
callback(new Error("请输入正确ip"));
return;
}
};
return {
form:{},
tableRules: {
ipAddress: { required: true, validator: vip, trigger: "blur" },
gateway: { required: true, validator: vip, trigger: "blur" },
},
portCfgList: [
{
id: 1,
portId: 1,
ipAddress: null,
gateway: null,
},
],
};
},
methods: {
submitForm() {
// 监听绑定的ref,通过里面一个fields的数组中的validateMessage来进行控制,当它不通过时,是你的错误信息
let fields = this.$refs.tableFormRef.fields;
let flag = true;
for (let i of fields) {
if (i.validateMessage) {
flag = false;
break;
}
}
console.log('【表格的校验是否通过】',flag)
this.$refs.tableFormRef.validate((valid) => {
console.log('【表格无mode用表单方法校验】',valid)
})
this.$refs.formRef.validate((valid) => {
console.log('【表单方法校验】',valid)
})
},
},
};
</script>
<style>
</style>
第一个日志和最后一个日志能正常出来,而中间的则提示需要mode才行