溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue中vee-validate插件如何使用

發(fā)布時(shí)間:2021-06-22 10:58:59 來源:億速云 閱讀:193 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“Vue中vee-validate插件如何使用”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Vue中vee-validate插件如何使用”這篇文章吧。

1.安裝

npm i vee-validate@4.0.3

2.導(dǎo)入

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

3.定義校驗(yàn)規(guī)則(最好是在utils文件夾中單獨(dú)封裝js文件導(dǎo)出)

// 創(chuàng)建js文件進(jìn)行導(dǎo)出
export default {
  // 校驗(yàn)項(xiàng)account
  account (value) {
    if (!value) return '不能為空'// 條件判斷,
    return true // 最后全部通過必須return true
  },
  password (value) {
    if (!value) return '請輸入密碼'
    if (!/^\w{6,24}$/.test(value)) return '密碼是6-24個(gè)字符'
    return true
  },
  mobile (value) {
    if (!value) return '請輸入手機(jī)號'
    if (!/^1[3-9]\d{9}$/.test(value)) return '手機(jī)號格式錯(cuò)誤'
    return true
  },
  code (value) {
    if (!value) return '請輸入驗(yàn)證碼'
    if (!/^\d{6}$/.test(value)) return '驗(yàn)證碼是6個(gè)數(shù)字'
    return true
  },
  isAgree (value) {
    if (!value) return '請勾選同意用戶協(xié)議'
    return true
  }
}

4.使用Form組件配置校驗(yàn)規(guī)則和錯(cuò)誤對象 (form 和 Field都是從插件中按需導(dǎo)出)

// validation-schema="mySchema"  配置校驗(yàn)規(guī)則
// v-slot:導(dǎo)出錯(cuò)誤對象
<Form
  :validation-schema="mySchema"
  v-slot="{ errors }"
>
 <!-- 表單元素 -->
</Form>

<script>
  import schema from '@/utils/vee-validate-schema'
  setup () {
    // 表單對象數(shù)據(jù)
    const form = reactive({
      account: null, // 賬號
      password: null // 密碼
    })
    // 校驗(yàn)規(guī)則對象
    const mySchema = {
      account: schema.account,
      password: schema.password
    }
    return { form, mySchema }
 } 
</script>

5.使用 Field 組件,添加表單項(xiàng)目校驗(yàn)

//1. 把input改成 `Field` 組件,默認(rèn)解析成input
//2. `Field` 添加name屬性,作用是指定使用schema中哪個(gè)校驗(yàn)規(guī)則
//3. `Field`添加v-model,作用是提供表單數(shù)據(jù)的雙向綁定
//4. 發(fā)生表單校驗(yàn)錯(cuò)誤,顯示錯(cuò)誤類名`error`,提示紅色邊框

<Field
      v-model="form.account"
      name="account" 
      type="text"
      placeholder="請輸入用戶名"
      :class="{ error: errors.account }" // 如果返回錯(cuò)誤信息,為true 顯示類error
    />
    <!-- <input type="text" placeholder="請輸入用戶名" /> -->

6.補(bǔ)充表單數(shù)據(jù)和驗(yàn)證規(guī)則數(shù)據(jù)

// 表單綁定的數(shù)據(jù)
const form = reactive({
  account: null, // 賬號
  password: null, // 密碼
  isAgree: true // 是否選中
})

// 聲明當(dāng)前表單需要的校驗(yàn)數(shù)據(jù)規(guī)則
const curSchema = reactive({
  account: schema.account, // 賬號
  password: schema.password, // 密碼
  isAgree: schema.isAgree // 是否選中
})

以上是“Vue中vee-validate插件如何使用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI