一、設計校驗方式:html
咱們表單驗證的rules通常封裝一個單獨的js文件,好比我以前寫的這個博客:vue
ElementUI使用問題記錄:設置路由+iconfont圖標+自定義表單驗證函數
能夠修改下:公共的校驗寫在公共裏面,個性化的校驗寫在methods裏面post
:rules="[rules.password,{validator:valPwd,trigger:'blur'}]"this
//先導入公共驗證文件 import {validator,getVeriCode} from '@/utils' //data裏面 data(){ return {rules:validator} } //在methods裏面定義新的驗證函數valPwd methods:{ valPwd(rule, value, callback) { if (!value) { callback(new Error('請再次輸入密碼')); } else if (value !== this.resetPassword.password) { callback(new Error('兩次輸入密碼不一致!')); } else { callback(); } } } //template裏面綁定驗證規則 <el-form-item prop="repeatPassword" :rules="[rules.password,{validator:valPwd,trigger:'blur'}]"> <el-input type="password" v-model="resetPassword.repeatPassword" placeholder="重複密碼"></el-input> </el-form-item>
二、同時校驗多個表單url
在保存某個頁面時,讓頁面中的兩個form都經過校驗才能保存,方法其實挺多的,主要是看下這個Promise的寫法spa
var p1=new Promise(function(resolve, reject) { this.$refs[form1].validate((valid) => { if(valid){ resolve(); } }) }); var p2=new Promise(function(resolve, reject) { this.$refs[form2].validate((valid) => { if(valid){ resolve(); } }) }); Promise.all([p2,p1]).then(function(){ alert("驗證經過了"); });
三、只驗證表單裏面部份內容:好比咱們須要獲取驗證碼的時候,就只須要驗證表單裏面的手機號就好了設計
getCode(){ this.$refs['resetPassword'].validateField('phone',(validMessage)=>{ if(validMessage != ""){ return false; } this.codeDisabled = true; let countTime = setInterval(() => { --this.countdown; if(this.countdown == 0){ clearTimeOut(countTime); this.countdown = 60; this.codeDisabled = false; return; } },1000); }) }
看文檔裏面都有的code
咱們也能夠封裝一下orm
//獲取驗證碼
export const getVeriCode = (vueInstance,formName,phone) => { vueInstance.$refs[formName].validateField('phone',(validMessage)=>{ if(validMessage != ""){ return false; } getVeriCodeApi(phone).then((res) =>{ if(res.status === 200){ vueInstance.$message({ message:'驗證碼已發送,請注意查收。', type:'success' }) } }) vueInstance.codeDisabled = true; let countTime = setInterval(() => { --vueInstance.countdown; if(vueInstance.countdown == 0){ clearInterval(countTime); vueInstance.countdown = 60; vueInstance.codeDisabled = false; return; } },1000); }) } //調用
getCode(){ getVeriCode(this,'login_code',this.login_code.phone) },