登录页面
登录表单
<template>
<a-form ref="formRef" :label-col="labelCol" :wrapper-col="wrapperCol">
<a-form-item label="用户名">
<a-input type="text" />
</a-form-item>
<a-form-item label="密码">
<a-input type="password" />
</a-form-item>
<a-form-item :wrapper-col="{ span: 14, offset: 4 }">
<a-button type="primary" @click="onSubmit">登录</a-button>
</a-form-item>
</a-form>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
const formRef = ref();
const onSubmit = () => {};
return {
labelCol: { span: 4 },
wrapperCol: { span: 14 },
onSubmit,
};
},
});
</script>
ref拿到表单的引用
// 声明ref
const formRef = ref()
<a-form ref="formRef" :label-col="labelCol" :wrapper-col="wrapperCol">
</a-form>
定义我们表单的数据格式
interface IFormState {
username: string;
password: string;
}
初始化我们的数据
setup() {
const formState = reactive<IFormState>({
username: "",
password: "",
});
return {
formState,
};
},
绑定我的数据
强调一下,为什么这么写,为了达到双向数据绑定mvvm
<a-form
:model="formState"
>
<a-form-item label="用户名">
<a-input type="text" v-model:value="formState.username" />
</a-form-item>
<a-form-item label="密码">
<a-input type="password" v-model:value="formState.password" />
</a-form-item>
</a-form>
定义我们的校验规则
const rules = {
username: [],
password: [],
};
使用规则
<a-form
:model="formState"
:rules="rules"
>
<a-form-item label="用户名" name="username">
<a-input type="text" v-model:value="formState.username" />
</a-form-item>
<a-form-item label="密码" name="password">
<a-input type="password" v-model:value="formState.password" />
</a-form-item>
</a-form>
最终渲染的HTML
a-form-item 他的name值和formState中的成员变量要对应
完善校验规则
const rules = {
username: [
{
type: "string",
required: true,
message: "用户名不可以为空",
trigger: "blur",
},
{
type: "string",
min: 2,
max: 20,
message: "用户名长度在2-20位",
trigger: "blur",
},
],
password: [
{
type: "string",
required: true,
message: "密码不可以为空",
trigger: "blur",
},
{
type: "string",
min: 6,
max: 20,
message: "密码长度在6-20位",
trigger: "blur",
},
],
};
校验方式的参考文档 async-validator
学会定位问题
校验表单数据
//依赖
import { ValidateErrorEntity } from "ant-design-vue/lib/form/interface";
const onSubmit = () => {
formRef.value
.validate()
.then(() => {
console.log(toRaw(formState));
})
.catch((error: ValidateErrorEntity<IFormState>) => {
console.log(error);
});
};