學習vee-validate,首先可以去閱讀官方文檔,更為詳細可以閱讀官網中的規則。英文文檔可能會有不理解的地方,推薦大家看這篇博客
下面來簡單總結一下我的使用:
一、安裝
npm install vee-validate@next --save
后面加@next是為了安裝vue2.0的版本
二、引入
我使用的是vue-cli腳手架工具,需要在main.js中
import VeeValidate from 'vee-validate'Vue.use(VeeValidate);
三、簡單的使用
這個時候其實已經可以使用了,先上demo
<div> <label for="email">郵箱:</label> <input v-validate ="'required|email'" type="text" id="email" name="myEmail"> </div> <span v-show="errors.has('myEmail')">{{ errors.first('myEmail')}}</span>解釋一下:v-validate后面的required和email是官方已經規定好的幾種默認錯誤類型中的兩個,這個可以閱讀官方文檔。
span中用到了errors的幾個方法,這里的參數都是定義了驗證規則的表單的name。列舉幾個errors的方法:
1、first(‘field')
field中(也就是剛剛說過的name表單)中的第一個錯誤
2、collect(‘field')
field中所有的錯誤
3、has(‘field')
field中是否有錯誤
4、all()
當前表單中的所有錯誤
5、any()
當前表單中是否有錯誤
6、count()
當前表單中的錯誤數量
7、clear()
清除當前表單中的所有錯誤
四、使用中文錯誤提示
沒有配置過的錯誤提示默認使用英文顯示的,如果想要用中文顯示需要我們手動配置一下
首先還是在main.js中引入
import zh_CN from 'vee-validate/dist/locale/zh_CN'import { Validator } from 'vee-validate';緊接著再加一句
Validator.addLocale(zh_CN);
最后需要把第一步的Vue.use(VeeValidate)改為
Vue.use(VeeValidate, { locale: 'zh_CN',});現在錯誤提示已經是中文了
五、配置組件
上一點中的配置中文其實已經是對組件的配置了,再說一說其他的配置。
//配置const config = { errorBagName: 'errors', // change if property conflicts. fieldsBagName: 'fields', delay: 0, locale: 'zh_CN', strict: true, enableAutoClasses: false, classNames: { touched: 'touched', // the control has been blurred untouched: 'untouched', // the control hasn't been blurred valid: 'valid', // model is valid invalid: 'invalid', // model is invalid pristine: 'pristine', // control has not been interacted with dirty: 'dirty' // control has been interacted with }, events: 'blur', inject: true};Vue.use(VeeValidate, config);
新聞熱點
疑難解答
圖片精選