使用formRef
<a-form ref="formRef" :model="modal.formQuery">
import type { FormInstance } from 'ant-design-vue'
const formRef = ref<FormInstance>()
const testForm = () => {
formRef.value
?.validate(['word']) // 不加参数,会校验全部规则
.then((res) => {
console.log('通过', res)
})
.catch((err) => {
console.log('失败', err)
})
}
// 子组件初始化示例
const init = () => {
formRef.value?.resetFields() // 初始化重置表单
}
defineExpose({ getLogisticsTemplateHandle }) // 导出该子组件方法
// 父组件监听方法
<Child ref="childInitRef" @init="childInit" />
import { nextTick } from 'vue'
type childTemplate = {
init: () => void
}
const childInitRef = ref<childTemplate>() // 绑定子组件的ref
const childInit = () => {
nextTick(() => {
if (childInitRef.value) childInitRef.value.init() // 直接调用子组件的init初始化方法
})
}
使用useForm
<template>
<a-form :label-col="labelCol" :wrapper-col="wrapperCol">
// 使用 v-bind="validateInfos.type" 绑定需要校验的数据
<a-form-item label="Activity name" v-bind="validateInfos.name">
<a-input v-model:value="modelRef.name" />
</a-form-item>
<a-form-item label="Activity zone" v-bind="validateInfos.region">
<a-select v-model:value="modelRef.region" placeholder="please select your zone">
<a-select-option value="shanghai">Zone one</a-select-option>
<a-select-option value="beijing">Zone two</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="Activity type" v-bind="validateInfos.type">
<a-checkbox-group v-model:value="modelRef.type">
<a-checkbox value="1" name="type">Online</a-checkbox>
<a-checkbox value="2" name="type">Promotion</a-checkbox>
<a-checkbox value="3" name="type">Offline</a-checkbox>
</a-checkbox-group>
</a-form-item>
<a-form-item :wrapper-col="{ span: 14, offset: 4 }">
<a-button type="primary" @click.prevent="onSubmit">Create</a-button>
<a-button style="margin-left: 10px" @click="resetFields">Reset</a-button>
</a-form-item>
</a-form>
</template>
<script lang="ts">
import { defineComponent, reactive, toRaw } from 'vue';
import { Form } from 'ant-design-vue';
const useForm = Form.useForm;
export default defineComponent({
setup() {
const modelRef = reactive({
name: '',
region: undefined,
type: [],
});
const rulesRef = reactive({
name: [
{
required: true,
message: 'Please input name',
},
],
region: [
{
required: true,
message: 'Please select region',
},
],
type: [
{
required: true,
message: 'Please select type',
type: 'array',
},
],
});
// 引入需要的方法,validateInfos绑定校验数据、validate规则验证、resetFields重置表单
const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef, {
onValidate: (...args) => console.log(...args),
});
const onSubmit = () => {
// 直接使用引入的`validate`进行校验
validate()
.then(() => {
console.log(toRaw(modelRef));
})
.catch(err => {
console.log('error', err);
});
};
return {
labelCol: { span: 4 },
wrapperCol: { span: 14 },
validateInfos,
resetFields,
modelRef,
onSubmit,
};
},
});
</script>
两种rules
定义方式
定义在form-item
<a-form-item
label="Username"
name="username"
:rules="[{ required: true, message: 'Please input your username!' }]"
>
<a-input v-model:value="formState.username" />
</a-form-item>
定义在form
<a-form
ref="formRef"
name="custom-validation"
:model="formState"
:rules="rules"
@finish="handleFinish"
@validate="handleValidate"
@finishFailed="handleFinishFailed"
></a-form>
import type { Rule } from 'ant-design-vue/es/form'
// 统一定义一个`rules`
const rules: Record<string, Rule[]> = {
pass: [{ required: true, validator: validatePass, trigger: 'change' }],
checkPass: [{ validator: validatePass2, trigger: 'change' }],
age: [{ validator: checkAge, trigger: 'change' }],
}
// 提取`validator`规则,独立定义`pass`
const validatePass = async (_rule: Rule, value: string) => {
if (value === '') {
return Promise.reject('Please input the password'); // eslint会报错
return Promise.reject(new Error('Please input the password')); // 加个new Error()
} else {
if (formState.checkPass !== '') {
formRef.value.validateFields('checkPass');
}
return Promise.resolve();
}
}
表单校验方法
<a-form ref="formRef" :model="formState"> // 1 form上绑定ref
import { FormInstance } from 'ant-design-vue' // 2 引入ts类型
const formRef = ref<FormInstance>() // 3 定义变量
formRef.value?.validate().then(() => {}).catch(() => {}) // 4 使用校验