You need to enable JavaScript to run this app. Vue中多ValidationObserver表单校验问题及优化方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 09:00:00