vue3ant中a-moadl表单校验
时间: 2024-06-03 17:03:19 浏览: 158
以下是在Vue 3中使用Ant Design Vue进行表单校验的示例:
```vue
<template>
<a-modal v-model:visible="modalVisible" title="表单校验示例">
<a-form :form="form" @submit="handleSubmit">
<a-form-item label="用户名" name="username" :rules="[{ required: true, message: '请输入用户名' }]">
<a-input v-model:value="form.username" />
</a-form-item>
<a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码' }]">
<a-input-password v-model:value="form.password" />
</a-form-item>
<a-form-item>
<a-button type="primary" html-type="submit">提交</a-button>
</a-form-item>
</a-form>
</a-modal>
</template>
<script>
import { ref } from 'vue';
import { AModal, AForm, AFormItem, AInput, AInputPassword, AButton } from 'ant-design-vue';
export default {
components: {
AModal,
AForm,
AFormItem,
AInput,
AInputPassword,
AButton,
},
setup() {
const form = ref(null);
const modalVisible = ref(false);
const handleSubmit = () => {
form.value.validateFields((errors, values) => {
if (!errors) {
// 表单校验通过,执行提交逻辑
console.log(values);
modalVisible.value = false;
}
});
};
return {
form,
modalVisible,
handleSubmit,
};
},
};
</script>
```
在上述示例中,我们使用了Ant Design Vue的`AForm`、`AFormItem`、`AInput`、`AInputPassword`和`AButton`组件来构建表单。通过在`AFormItem`组件上设置`rules`属性,我们可以定义表单项的校验规则。在提交表单时,我们使用`validateFields`方法来进行表单校验,如果校验通过,则执行提交逻辑。
阅读全文