vee-validate 是為 Vue.js 量身打造的表單校驗框架,允許您校驗輸入的內(nèi)容并顯示對應的錯誤提示信息。它內(nèi)置了很多常見的校驗規(guī)則,可以組合使用多種校驗規(guī)則,大部分場景只需要配置就能實現(xiàn)開箱即用,還支持自定義正則表達式。而且支持 40 多種語言,對本地化、多語言支持非常友好。
國內(nèi)餓了么團隊開源項目 Element UI 就用到了 vee-validate。
vee-validate官網(wǎng):https://baianat.github.io/vee-validate/
使用方法
可查看官網(wǎng)文檔(https://baianat.github.io/vee-validate/)或者查看這一篇文章(https://blog.givebest.cn/javascript/2019/04/20/vue.js-nuxt.js-use-vee-validate.html)。
組件內(nèi)使用 Vee-validate
子組件
<template> <div> <input placeholder="請輸入姓名" v-model="username" name="username" v-validate="'required'" :error-message="errors.first('username')" /> </div></template><script>export default { name: "Username", data() { return { username: '' } }, methods: { // 表單校驗 validateForm() { return this.$validator.validateAll(); }, }};</script>父組件
<template> <div> <Username ref="usernameComponent" /> <Password ref="passwordComponent" /> <div> <button @click="onSubmit">提交校驗</button> </div> </div></template><script>import Username from "~/components/username.vue"import Password from "~/components/password.vue"export default { components: { Username, Password }, data() { return {} }, methods: { onSubmit (e) { e.preventDefault() // 阻止默認事件 // 父組件觸發(fā)子組件校驗,并通過 Promise 返回值 let vf1 = this.$refs.usernameComponent.validateForm() let vf2 = this.$refs.passwordComponent.validateForm() // 提交表單前,校驗所有子組件,全部通過才允許下面操作 Promise.all([vf1, vf2]).then(result => { // 有一個組件未通過,就提示錯誤信息 if (result.indexOf(false) > -1) { console.log("全部校驗未通過") return } // 校驗全部通過處理 console.log("全部校驗通過") }) }, }};</script>總結(jié)
其實組件內(nèi)使用 Vee-validate 校驗很方便,主要問題可能是父組件怎么觸發(fā)子組件內(nèi)的校驗,并獲取校驗結(jié)果。這里用到 Vue.js 里的 ref 特性,給子組件賦值一個 ID 引用,然后就可以使用 this.$refs.childComponent 獲得子組件實例引用,再分別調(diào)起子組件寫好的校驗方法,如:
/**父組件觸發(fā)子組件校驗,并通過 Promise 返回值*/let vf1 = this.$refs.usernameComponent.validateForm() // 父組件調(diào)用 usernameComponent 組件里的 validateForm 方法let vf2 = this.$refs.passwordComponent.validateForm() // 父組件調(diào)用 passwordComponent 組件里的 validateForm 方法
新聞熱點
疑難解答
圖片精選