一、普通校验
绑定ref:ref="editRef"
<el-form label-position="top" :model="value" ref="editRef">
<el-form-item class="detail__modify">
<el-input v-model="out.outType"></el-input
>
</el-form-item>
</el-form>
...
提交时校验:editRef.value.validate()
const editRef = ref();
editRef.value.validate().then(async function () {
try {
await fetchDetail({...param})
}
...
如果需要取消校验,比如取消表单编辑的时候,就需要重置表单校验,否则可能会有校验信息提示。此时使用 editRef.value.resetFields();
function cancel(): void {
editRef.value.resetFields();
handleClear();
ctx.emit('close');
}
二、循环表单项的校验
请求到的数据在表单里循环展示,每条数据都需要一个表单项进行展示,对每个循环出来的表单项分别进行校验。
循环的数据为value.outStations
, props中outStations是循环的数组,index是循环的index,后边拼接的是需要校验对象的字段名也即 v-model="out.type"
中绑定的字段名。
<div v-for="(out, index) in value.outStations" :key="index">
<div class="platform">
<el-form-item
label="Off-app platforms"
:prop="`outStations.${index}.type`"
:rules="
[COOPERATION.BR_TeleKwai_Partner_BR, COOPERATION.IN_Family__Group].includes(
Number(value.agreementId)
)
? []
: [{ required: true, message: 'Required', trigger: 'blur' }]
"
>
<el-input v-model="out.outType"></el-input>
</el-form-item>
...
<el-form-item>..</el-form-item>
....
</div>
</div>
rules是校验,可以为每个form-item单独设置(如上代码),也可以在setup中设置(如下述所示)。校验方式都是一样的。
在setup中设置rules:
-
校验规则为静态校验
script:
const dataRules = reactive({
outType: [{ required: true, message: 'Required', trigger: 'blur' }],
});
template:
<el-form-item
:prop="`outStations.${index}.type`"
:rules="dataRules.outType"
></el-form-item>
-
校验规则根据条件动态校验
比如根据循环出的值判断是否校验,可以使用函数返回校验规则:
script:
// 传入当前校验的字段(type)以及判断条件(id )
const funcRules = function (type: string, id: any): any {
if (type === 'outType' || type === 'fansCont') {
return [
COOPERATION.BR_TeleKwai_Partner_BR,
COOPERATION.IN_Family__Group,
].includes(Number(id))
? []
: [{ required: true, message: 'Required', trigger: 'blur' }];
}
};
template:
<el-form-item
:prop="`outStations.${index}.type`"
:rules="funcRules('outType', value.agreementId)"
>
> <el-input v-model="out.outType"></el-input
></el-form-item>
<el-form-item
:prop="`outStations.${index}.fansCont`"
:rules="funcRules('fansCont', value.agreementId)"
>
> <el-input v-model="out.fansCount"></el-input
></el-form-item>
三、循环表单项添加了异步校验函数,全部校验通过才能提交
循环表单项里,如果给每个form-item 添加其他异步的校验方法,提交之前需要判断所填数据是否满足条件,才能提交,可使用Promise.all 方法。
template:
<ks-form-item
:prop="`outStations.${index}.userId`"
rules="
[{ required: true, message: 'Required', trigger: 'change' }]
"
>
<ks-input
v-model="out.userId"
placeholder="ID"
@input="checkVerify(out)"
></ks-input>
</ks-form-item>
checkVerify
异步校验失败则捕获异常,返回false作为判断值。
这里使用了 @input
方法,一开始想到的使用@change
方法,但是校验结果blur之后才能触发,后又改用@keyup
方法,但是复制过去的值不会触发校验。最后才想到用 @input
方法 ,可以输入实时校验。
Script:
async function checkVerify(info: any): Promise<any> {
try {
await fetchOutstation(info);
} catch (e) {
message.error(e);
return false;
}
}
...
// 对提交的对象数组的每一项都执行一次异步校验函数,得到一个执行结果为promise的数组
const promiseAllArr = addForm.agreementOutInfos.map((info: any) => {
return checkVerify(info);
});
// 使用Promise.all 得到函数执行结果
const result = await Promise.all(promiseAllArr);
const invalid = result.some((d: any) => d === false);// 如果都校验通过,result数组里没有false 值
这里每个form 如果:model 绑定的数据是相同的,但是校验的ref值不能相同,ref是获取dom节点,对每个form 需要唯一绑定。 表单项要么写在一个form 里,要么分成几个form之后绑定不同的ref。
-
Vue单文件组件中多个同名的ref属性,this.$refs的取值及其使用注意事项
下面是绑定多个表单之后,需要每个都校验通过才能进行下一步。 原理同上。
Promise.all([editRef1.value, editRef2.value, editRef3.value].map(item => item.validate())).then(async function () { ... }
四、循环表单中单个表单的独立校验
根据请求到的数据循环创建表单,每个表单都应该是独立的,校验规则也是独立的。
前面提到的表单普通校验中,通过定义 const editRef = ref();
给表单form绑定ref="editRef"
得到整个表单的校验对象以及校验相关的方法。 如果表单是循环出来的,则该ref也应该是动态绑定的。
重新定义editRef
,使用数组保存每个表单的指向,数组项应该为Ref类型,可挂载dom节点相关的方法。
const editRef = ref<Array<Ref>>([]);
...
// 请求到数据赋值给ruleForm.agreementInfos之后,遍历该对象为 editRef 赋值:
ruleForm.agreementInfos.forEach((item: any, index: number) => {
editRef.value.push(ref(`editRef${index}`)); // editRef[0] = ref(`editRef0`)
});
循环表单template,每个form绑定ref为:ref="editRef[idx]"
<div
v-for="(value, idx) in ruleForm.agreementInfos"
:key="value.agreementId"
>
<ks-form label-position="top" :model="value" :ref="editRef[idx]">
<ks-form-item>
<ks-input v-model="value.memberName"></ks-input
>
</ks-form-item>
</ks-form>
<div>
提交时找到当前表单,该表单独立校验通过之后才能将表单数据提交到服务器。关键点: editRef.value[idx].value.validate()
script:
async function SubmitAgreementInfo(agreementId: any): Promise<any> {
let idx = -1;
const currentData: any = ruleForm.agreementInfos?.forEach((item: any, index: number) => {
if (item.agreementId === agreementId) {
idx = index;
}
});
editRef.value[idx].value.validate().then(async function () {
await fetchSubmit({ param });
});
}