Vue中多ValidationObserver表单校验问题及优化方案咨询
问题原因
原有triggerSubmit采用Promise嵌套写法,仅对第一个profile校验的失败场景做了错误捕获,workInfo、personalInfo校验失败时没有对应处理分支,因此不会打印失败日志,同时嵌套结构冗余、可读性差。另外代码将this.showModal = false放在异步校验逻辑外侧,会在校验未完成时提前执行赋值,逻辑不够严谨。
修复&优化实现
推荐用async/await改写,逻辑更清晰,所有失败场景可统一处理:
并行校验版本(校验效率更高,三个表单同时校验)
async triggerSubmit() { try { const [profileValid, workInfoValid, personalInfoValid] = await Promise.all([ this.$refs.profile.validate(), this.$refs.workInfo.validate(), this.$refs.personalInfo.validate() ]) if (profileValid && workInfoValid && personalInfoValid) { // 全部校验通过执行成功逻辑 this.showModal = true this.isUpdatedWorkInfo = true this.isUpdatedPersonalInfo = true this.isUpdatedProfile = true } else { // 任意校验失败执行失败逻辑 this.showModal = false console.log('Failed') } } catch (err) { // 校验过程出现异常也走失败逻辑 this.showModal = false console.log('Failed') } }
顺序校验版本(前一个校验失败就终止后续校验,符合原有嵌套逻辑的执行顺序)
async triggerSubmit() { try { const profileValid = await this.$refs.profile.validate() if (!profileValid) throw new Error() const workInfoValid = await this.$refs.workInfo.validate() if (!workInfoValid) throw new Error() const personalInfoValid = await this.$refs.personalInfo.validate() if (!personalInfoValid) throw new Error() // 全部校验通过 this.showModal = true this.isUpdatedWorkInfo = true this.isUpdatedPersonalInfo = true this.isUpdatedProfile = true } catch (err) { // 任意环节失败统一处理 this.showModal = false console.log('Failed') } }
内容的提问来源于stack exchange,提问作者Lucas
相关产品推荐
相关产品推荐

