vue el-from校验成功但是 return不管用?

async handleSubmit() {
      const flag = await this.$refs.form.validate().catch((e) => e)
      if (!flag) return
      this.loading = true
      try {
        await queryVipStandardEdit({
          ...this.form,
        })
        this.$message.success(this.$t('pls_operate_successful') + '!')
        this.close('success', true)
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },

校验生效了,但是if (!flag) return不管用,依然回走下面方法,哪里写错了

阅读 1.7k
avatarAI BotBETA

根据您提供的代码,我注意到在 handleSubmit 方法中,您尝试使用 if (!flag) return 来判断校验是否成功。然而,您在 validate 方法上调用 return,这实际上是终止方法的执行并立即返回。如果您想要在方法执行完毕后立即返回,可以使用 return 语句,而不是调用它。

所以,您可以将代码修改为:

async handleSubmit() {
  const flag = await this.$refs.form.validate().catch((e) => e)
  if (!flag) return; // 修改这一行
  this.loading = true
  try {
    await queryVipStandardEdit({
      ...this.form,
    })
    this.$message.success(this.$t('pls_operate_successful') + '!')
    this.close('success', true)
  } catch (error) {
    this.$message.error(error)
  } finally {
    this.loading = false
  }
},

这样,当校验成功时,方法将正常执行完毕并返回。如果校验失败,方法将立即返回并处理错误。

4 个回答

catch 去掉就行了

async handleSubmit() {
  await this.$refs.form.validate();

  // ...
}

未通过的时候 flag返回的是校验规则列表 你可以打印出来看看

可以这样写

async handleSubmit() {
      //如果校验不通过,就会抛异常
      await this.$refs.form.validate()
      this.loading = true
      try {
        await queryVipStandardEdit({
          ...this.form,
        })
        this.$message.success(this.$t('pls_operate_successful') + '!')
        this.close('success', true)
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },

await之后就表示校验成功了

async handleSubmit() {
    await this.$refs.form.validate()
    try {
        this.loading = true
        const params = { ...this.form }
        await queryVipStandardEdit(params)
        this.$message.success(this.$t('pls_operate_successful') + '!')
        this.close('success', true)
    } catch (error) {
        this.$message.error(error)
    } finally {
        this.loading = false
    }
},
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题