原理
为 rules 属性传入约定的验证规则,并将 form-Item 的 prop 属性设置为需要验证的特殊键值 :model和:rules中字段的名称需要一致
示例:
< template> < el-form ref = " ruleFormRef" :model = " ruleForm" :rules = " rules" > < el-form-item label = " 用户名" prop = " name" > < el-input v-model = " ruleForm.name" /> </ el-form-item> < el-form-item> < el-button type = " primary" @click = " submitForm(ruleFormRef)" > Create </ el-button> </ el-form-item> </ el-form>
</ template> < script lang = " ts" setup >
import { reactive, ref } from "vue" ;
import type { FormInstance } from "element-plus" ; const ruleFormRef = ref< FormInstance> ( ) ;
const ruleForm = reactive ( { name : ""
} ) ; const rules = reactive ( { name : [ { required : true , message : "请输入用户名" , trigger : "blur" } , { min : 3 , max : 5 , message : "用户名长度在 3 到 5 个字符" , trigger : "blur" } ]
} ) ; const submitForm = async ( formEl : FormInstance | undefined ) => { if ( ! formEl) return ; await formEl. validate ( ( valid, fields ) => { if ( valid) { console. log ( "数据正常" ) ; } else { console. log ( "数据有误" , fields) ; } } ) ;
} ;
</ script>