1.在表单中添加动态校验

<a-form
          :model="addUserForm"
          name="basic"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span:17  }"
          autocomplete="off"
          ref="addUserFormRef"//必填项在setup中定义addUserFormRef
          :rules="addUserRules"//校验规则
      >
        <a-form-item
            label="用户名"
            name="username"//name也是必填项,name的值是和校验规则里面的值想同
        >
          <a-input v-model:value="addUserForm.username" placeholder="请输入用户名" />
        </a-form-item>
</a-form>

2.setup中定义校验规则并返回

addUserFormRef :'',
const addUserRules = {
      username: [
        { required: true,  trigger: 'blur', message: '请输入用户名!'},
        { min: 1, max: 6, trigger: 'blur', message: '用户名长度是 1-6 位字符!'}
      ],}

3.重置表单

//在vue3中重置表单要借助于proxy
let {proxy} = getCurrentInstance();
proxy.$refs.addUserFormRef.resetFields();

4.点击确定同时校验表单里的item项

let {proxy} = getCurrentInstance();//记得引入getCurrentInstance
proxy.$refs.addUserFormRef.validate().then((res)=>{
         message.success('添加用户表单校验成功!');
      }).catch(()=>{
        message.error('添加用户表单校验失败!');
      });

Logo

前往低代码交流专区

更多推荐