最近公司的項目會有大量的表單需要輸入很多信息。
比如下面的表單:
像這種,三個表單點確定同時提交,因而需要對三個表單進行同時驗證,一個驗證不通過,接口就走不通。
我知道的有兩種方法:
第一種方法是通過promise.all(),通過promise進行同步驗證。代碼示例度娘有很多。
我使用的是第二種方法,代碼如下:
1 addBaseInfo(){ 2 that.$refs['store'].validate((valid) => { //第一個表單ref="store” 5 if (valid) { 6 this.titleFormValid = true //如果通過,加個true相當於開關判斷 7 } 8 }); 9 if(this.store.type==1){ 10 that.$refs['school'].validate((valid) => { //第二個表單ref='school' 11 if(valid){ 12 that.customFormValid = true //同上 13 } 14 }); 15 }else if(this.store.type==3){ 16 that.$refs['company'].validate((valid) => { 17 if(valid){ 18 that.customFormValid = true 19 } 20 }); 21 }else{ 22 that.$refs['community'].validate((valid) => { 23 if(valid){ 24 that.customFormValid = true 25 } 26 }); 27 }; 28 that.$refs['dynamicValidateForm'].validate((valid) => { //第三個表單ref='dynamicValidateForm' 29 if(valid){ 30 that.orangerFormValid = true //同上 31 } 32 }); 33 if (this.titleFormValid && this.customFormValid && this.orangerFormValid) { //這是最關鍵的,當這三個表單都通過,之間是且關系,才能走下一步 34
35 } 36 },
通過加個true/false判斷,表示表單是否可是驗證的方法,親測有效。