1.安装
2.导入组件,注册为局部组件
import { Form, Field } from 'vee-validate'components:{Form, Field}
3.基本结构
Form 就是表单, Field就是表单项
<Form><Field v-model="formData.mobile" name="mobile" type="text" placeholder="请输入手机号" /><Field v-model="formData.password" name="password" type="password" placeholder="请输入密码" /></Form>// 以前的Field的位置是input
4.定义验证规则
整体用一个对象包起来,每条规则就是一个函数。具体格式如下:
- 参数1:是要验证的值,参数2:是验证对象{field, form}
- 返回值:true表示通过验证,返回字符串表示校验错误。
const schema = {mobile (value) {if (!value) return '请输入手机号'if (!/^1[3-9]\d{9}$/.test(value)) return '手机号格式错误'return true},password (value) {if (!value) return '请输入密码'if (!/\d{6}$/.test(value)) return '密码格式错误'return true},isAgree (value) {return value || '不答应可不行'}}
5.使用规则
- 用Form去替换原来的form, 用Field去替换原input元素
- Form中要使用:ref, validation-schema, v-slot
- Field中设置v-model, name, class
- Form中要使用:ref, validation-schema, v-slot
补充dom结构来存放校验错误提示(在element, vant等组件库中,我们是不需要写的)
<!--ref: 引用;后边手动兜底校验要使用validation-schema: 用来指定校验规则(这里的规则)v-slot: 作用域插槽,如果校验失败,errors中会保存校验失败的结果--><Form ref="target" :validation-schema="schema" v-slot="{errors}"><!-- 省略其他 ... --><!--Field: v-model:双向绑定数据项name:指定要校验的字段:class="{error:errors.mobile}" 如果校验失败,就补充error类动态绑定class用来约定错误发生时的样子 --><Fieldv-model="formData.mobile"type="text"name="mobile"placeholder="请输入手机号":class="{error:errors.mobile}"/><!-- 约定显示校验错误结果 --><div class="error" v-if="errors.mobile">{{errors.mobile}}</div><!-- 省略其他 ... --><a @click="login()" href="javascript:;" class="btn">登 录</a></Form>
6.手动兜底校验
const target = ref(null) // 定义引用属性 <Form ref="target"const login = () => {// Form 组件提供了一个 validate 函数作为整体表单校验,返回的是一个promisetarget.value.validate().then((res) => {console.log('表单校验结果', res)})}
7.学习使用-vee-validate-拓展使用
7.1联合第三方组件
```javascript
``` 7.2提取校验规则
将schame全部提取出来,放在一个独立的文件中
src/utils/validate.js ```javascript export const account = (value) => { if (value === ‘’) { return ‘用户名不能为空,请检查!’ } return true }
export const mobile = (value) => { if (!value) return ‘请输入手机号’ if (!/^1[3-9]\d{9}$/.test(value)) return ‘手机号格式错误’ return true }
export const password = (value) => { if (!value) return ‘请输入密码’ if (!/\d{6}$/.test(value)) return ‘密码格式错误’ return true }
export const isAgree = (value) => { return value || ‘不答应可不行’ }
使用:```javascriptimport { account, isAgree } from '@/utils/validate'const schema = {account: account,isAgree: isAgree}
setup () {// 省略其他 ...const target = ref(null)// 表单对象数据const form = reactive({isAgree: true,account: null,password: null,mobile: null,code: null})// 校验规则对象const schema = {account: schemaRules.account,password: schemaRules.password,mobile: schemaRules.mobile,code: schemaRules.code,isAgree: schema.isAgree}return { target, schema, formData}}
