记录使用 Vue 3 + vee-validate 进行表单处理与验证的基本方式,适用于登录注册等典型场景。


一、安装 vee-validate

npm install vee-validate yup
  • vee-validate 负责表单验证逻辑
  • yup 是配套的字段规则定义库

二、基本使用方式

<script setup>
import { useForm, useField } from 'vee-validate'
import * as yup from 'yup'

const schema = yup.object({
  username: yup.string().required(),
  password: yup.string().min(6).required()
})

const { handleSubmit } = useForm({ validationSchema: schema })

const { value: username, errorMessage: usernameError } = useField('username')
const { value: password, errorMessage: passwordError } = useField('password')

const onSubmit = handleSubmit(values => {
  console.log('提交成功', values)
})
</script>

<template>
  <form @submit.prevent="onSubmit">
    <div>
      <input v-model="username" placeholder="用户名" />
      <span class="error">{{ usernameError }}</span>
    </div>
    <div>
      <input type="password" v-model="password" placeholder="密码" />
      <span class="error">{{ passwordError }}</span>
    </div>
    <button type="submit">提交</button>
  </form>
</template>

三、字段校验逻辑

字段值和错误信息是分别解构出来的:

const { value: xxx, errorMessage: xxxError } = useField('字段名')

每个字段都会自动响应校验规则,并暴露错误提示。


四、支持的验证规则(yup)

常用规则:

  • string().required():必填
  • min(n):最小长度
  • email():邮箱格式
  • matches(regex):正则
  • oneOf([...]):值限定范围

五、使用 watch 监听表单字段变化

watch(username, val => {
  // 字段变化时触发逻辑
})

配合响应式处理可以做一些动态反馈。


六、小结

vee-validate 配合 yup 使用方式清晰,字段绑定、校验逻辑分离。整体体验偏函数式,适配 Vue 3 的 Composition API 结构。