element-ui中的el-form表单验证,只在提交按钮点击时才进行验证
element-ui中的el-form表单验证,只有在提交按钮点击时才进行验证,这样会减少消耗
其实很简单,直接在el-input上加一个属性就行:validate-event="false"
Form 表单组件的表单属性都有这么一个属性
示例
<template>
<el-form
ref="fieldFormRef"
:model="fieldForm"
:rules="fieldRules"
label-position="top"
label-width="80px"
>
<el-form-item label="字段" prop="field">
<el-row style="width: 100%" :gutter="20">
<el-col :span="15">
<el-input
:validate-event="false" // !!!
size="small"
v-model="fieldForm.field"
placeholder="字段名称"
clearable
/>
</el-col>
<el-col :span="9" class="text-center">
<el-button size="small" @click="onAddField(fieldFormRef)"
>添加</el-button
>
</el-col>
</el-row>
</el-form-item>
</el-form>
</tempalte>
<script setup>
const fieldFormRef = ref(null);
const fieldForm = reactive({
field: "",
});
// 验证字段是否输入正确
const validateField = (rule, value, callback) => {
console.log("value", value);
if (value === "") {
callback(new Error("请输入字段"));
} else if (value.length > 15) {
callback(new Error("长度限制在1-15字"));
} else if (tableData.value.map((f) => f.field).includes(value)) {
callback(new Error("字段重复"));
} else {
callback();
}
};
const fieldRules = reactive({
field: [{ validator: validateField, trigger: "blur" }], // 将'blur'去掉,是鼠标失去焦点的时候会触发验证
});
// 在点击确定按钮的时候,触发函数,然后进行验证
const onAddField = async (formEl) => {
if (!formEl) return;
await formEl.validate((valid, fields) => {
console.log(valid, fields);
if (valid) {
console.log("success");
} else {
console.log("error submit!", fields);
}
});
};
</script>