Antd之表单校验

使用Antd进行表单校验,代码如下:

<template>
  <a-form
    :model="formState"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    ref="newFormRef"
    autocomplete="off"
  >
    <a-form-item
      label="模板名"
      name="name"
      has-feedback
      :rules="[{ required: true, message: '请输入模板名' }]"
    >
      <a-input v-model:value="formState.name" />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 10 }">
      <a-button type="primary" html-type="submit" @click="onSubmit">确认</a-button>
    </a-form-item>
  </a-form>
</template>

即设置表单的ref值,在form-item中设置校验规则,注意要设置form-item的name值。

然后在提交表单时根据ref值对表单进行校验,代码如下:

methods: {
  onSubmit(){
    this.$refs.newFormRef.validate().then(() => {
      console.log("submit!", this.formState, toRaw(this.formState));
      this.$emit("afterSavingToTemplate");
    });
  }
}

即可。

posted @ 2022-03-25 10:03  罗毅豪  阅读(517)  评论(0编辑  收藏  举报