表单验证的步骤:
- 给
form 设置属性 :rules :rules - 同时给需要验证的每个
form-item 设置属性 prop ,指向对应字段即可 prop="" form 标签里用v-model 双向绑定页面数据。form 标签里添加ref ,在这个范围内规则才生效,可以理解为id。- 在提交或保存时,添加方法,对整个表单进行校验,参数为检验完的回调,会返回一个
Boolean 表示成功与失败。
代码如下:
<el-form :rules="rules"
:model="ruleForm"
ref="formRef"
label-position="right">
<el-form-item label="车牌号:"
label-width="80px"
prop="plate_number">
<el-input v-model="ruleForm.plate_number"></el-input>
</el-form-item>
</el-form>
<el-button type="primary" @click="addOrderSubmit(ruleForm)">确定</el-button>
<script lang="ts">
import { defineComponent, ref, reactive, watch, onMounted, unref } from "vue";
export default defineComponent({
setup(){
const formRef = ref();
const ruleForm = reactive({plate_number: ""});
const rules = reactive({
plate_number: [{ validator: validatePlate }],
});
function addOrderSubmit(e) {
formRef.value.validate((valid: any) => {
if (valid) {
console.log("成功回调")
} else {
return false;
}
});
}
}
})
</script >
|