需求:点击登录、注册和找回密码等按钮发起请求后,如果返回错误,错误提示需要根据错误原因显示在对应的输入框下方(例えば用户已存在提示在用户信息的输入框下,与表单验证的错误统一样式。
使用:
参考:
async-validator: async-validator:表单校验
packages/components/form/src/form.vue · element-plus/element-plus - Gitee.com
具体实现:
1. 封装验证逻辑:
export const showCustomValidMsg = (formEle: FormInstance, errorObj: { errCode: string, errMsg: string }): void => {
let ruleKey = '';
if (['WRONG_AUTH_CODE', 'UNKNOWN_SCENE',].includes(errorObj.errCode)) {
ruleKey = 'authCode';
} else if (['USER_EXIST', 'USER_NOT_FOUND'].includes(errorObj.errCode)) {
ruleKey = 'user';
} else if (['LOGIN_FAILED'].includes(errorObj.errCode)) {
ruleKey = 'password';
}
if (ruleKey !== '') {
const ruleBackUp = formEle.rules[ruleKey];
formEle.rules[ruleKey] = [
{
required: true,
validator: (rule, value, callback) => {
callback(new Error(errorObj.errMsg));
}
},
]
formEle.validateField(ruleKey,()=>{})
formEle.rules[ruleKey] = ruleBackUp;
}
}
2. 在表单组件中引入、调用:
<template>
<el-form
ref="formRef"
:rules="rules"
>
<PhoneForm v-model="form.phone" />
<PasswordForm v-model="form.password" />
<SecurityCodeForm v-model="form.authCode" :phone="form.phone" />
<el-form-item style="margin-bottom: 0">
<PrimaryBtn @click="onSignUp(formRef)" />
</el-form-item>
</el-form>
</template>
<script setup lang="ts">
import { ruleList,showCustomValidMsg } from '@/data'
const onSignUp = (current) => {
if (!current) return
current.validate(async (valid) => {
if (valid) {
const [data,err] = await signUp(request)
if(data){
await queryCurrent()
}else{
showCustomValidMsg(current,err);
}
return false;
}
})
}
</script>
探讨欢迎━(*`∀´*)ノ亻!