vue实现表单单独移除一个字段验证

本文实例为大家分享了vue实现表单单独移除一个字段验证的具体代码,供大家参考,具体内容如下
下面的代码以登录功能为例。
功能描述: 用户输入密码时,失去焦点进行密码校验,当输入有误时,显示错误提示信息;只要密码值发生了变化,错误提示信息就移除。
通过watch监控password字段,实现实时移除。
vue2 模板语法代码如下:


vue2+composition-api 使用tsx语法开发,代码如下:
service.ts
export const initFormState = {username: '',password: ''} const validatePwd = (rule, value, callback) => {// 密码校验} export const formStateRules = {username: [{ required: true, message: '请输入用户名', trigger: 'blur'}],password: [{ required: true, validator: validatePwd, trigger: 'blur'}]}

index.tsx文件
import { onMounted, reactive, ref, watch } from "@vue/composition-api"; import { initFormState} from './service.ts'; export default defineComponent({setup (prop,{root}) {const formState= reactive({...initFormState, // 从service引入进来}) const formRef = ref(null); const submit = ()=> {// 表单校验const formValidate = await new Promise(resolve => {(formRef as any).value.validate((valid: boolean) => resolve(valid)); }); if(!formValidate) return; // 表单校验通过后进行的逻辑} const reset = () => {Object.keys(formState).map((key: string) => formState[key] = (initFormState as any)[key]); }// 监控password, 按需移除错误提示信息watch(() => formState.password, ()=> {const result = formState.password; if(result) {(formRef as any).value.clearValidate('password')}})return {formState,formRef,formStateRules,submit,reset}},render() {return (提交取消)} })

【vue实现表单单独移除一个字段验证】以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读