华域联盟 JAVA Vue vee-validate插件的简单使用

Vue vee-validate插件的简单使用

目录

1.安装

npm i [email protected]

2.导入

import { Form, Field } from 'vee-validate'

3.定义校验规则(最好是在utils文件夹中单独封装js文件导出)

// 创建js文件进行导出
export default {
  // 校验项account
  account (value) {
    if (!value) return '不能为空'// 条件判断,
    return true // 最后全部通过必须return true
  },
  password (value) {
    if (!value) return '请输入密码'
    if (!/^\w{6,24}$/.test(value)) return '密码是6-24个字符'
    return true
  },
  mobile (value) {
    if (!value) return '请输入手机号'
    if (!/^1[3-9]\d{9}$/.test(value)) return '手机号格式错误'
    return true
  },
  code (value) {
    if (!value) return '请输入验证码'
    if (!/^\d{6}$/.test(value)) return '验证码是6个数字'
    return true
  },
  isAgree (value) {
    if (!value) return '请勾选同意用户协议'
    return true
  }
}

4.使用Form组件配置校验规则和错误对象 (form 和 Field都是从插件中按需导出)

// validation-schema="mySchema"  配置校验规则
// v-slot:导出错误对象
<Form
  :validation-schema="mySchema"
  v-slot="{ errors }"
>
 <!-- 表单元素 -->
</Form>

<script>
  import schema from '@/utils/vee-validate-schema'
  setup () {
    // 表单对象数据
    const form = reactive({
      account: null, // 账号
      password: null // 密码
    })
    // 校验规则对象
    const mySchema = {
      account: schema.account,
      password: schema.password
    }
    return { form, mySchema }
 } 
</script>

5.使用 Field 组件,添加表单项目校验

//1. 把input改成 `Field` 组件,默认解析成input
//2. `Field` 添加name属性,作用是指定使用schema中哪个校验规则
//3. `Field`添加v-model,作用是提供表单数据的双向绑定
//4. 发生表单校验错误,显示错误类名`error`,提示红色边框

<Field
      v-model="form.account"
      name="account" 
      type="text"
      placeholder="请输入用户名"
      :class="{ error: errors.account }" // 如果返回错误信息,为true 显示类error
    />
    <!-- <input type="text" placeholder="请输入用户名" /> -->

6.补充表单数据和验证规则数据

// 表单绑定的数据
const form = reactive({
  account: null, // 账号
  password: null, // 密码
  isAgree: true // 是否选中
})

// 声明当前表单需要的校验数据规则
const curSchema = reactive({
  account: schema.account, // 账号
  password: schema.password, // 密码
  isAgree: schema.isAgree // 是否选中
})

以上就是Vue vee-validate插件的简单使用的详细内容,更多关于Vue vee-validate插件的资料请关注华域联盟其它相关文章!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » Vue vee-validate插件的简单使用

转载请保留出处和原文链接:https://www.cnhackhy.com/72263.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部