【问题标题】:Vee Validate 3 catch errors on form submitVee Validate 3 在表单提交时捕获错误
【发布时间】:2020-09-17 09:27:44
【问题描述】:

如果表单提交在 vee-validate 中失败,我该如何捕捉?我有以下组件

<template>
  <ValidationObserver tag='div' class='bg-white pt-6 pb-6 mb-4' v-slot='{ handleSubmit }'>

   <form
      @submit.prevent='handleSubmit(onSubmit)'
      class='mx-auto rounded-lg overflow-hidden pt-6 pb-6 space-y-10'
      :class="{'is-loading' : isLoading}"
    >
      <div class='flex flex-wrap -mx-3 mb-6'>
        <div class='w-full md:w-3/12 px-3 mb-6 md:mb-5'>
          <ValidationProvider v-slot='{ classes, errors }' rules='required' name='Anrede'>
          <CustomSelect :options='gender'
                        placeholder='Anrede *'
                        v-model='form.gender'
                        :class="classes"
          />
            <span class='text-mb-error font-medium text-sm italic'>{{ errors[0] }}</span>
          </ValidationProvider>
        </div>
</div>
   <div class='block'>
        <button
          class='bg-secondary hover:bg-secondary-200 text-white py-3 px-4 w-full mt-5 focus:outline-none'
          type='submit'
        >
          Registrieren
        </button>
      </div>
    </form>
  </ValidationObserver>
</template>

作为方法我有以下功能

 onSubmit () {
      alert()
      console.log(this.$refs.observer)

      this.$emit('onSendRegistration', this.form)
    }

如果表单有效但如果它失败则永远不会被执行。如果表单验证失败,我在哪里可以发现?

【问题讨论】:

  • 如果我的回答有任何帮助,请告诉我:)

标签: vue.js error-handling submit vee-validate


【解决方案1】:

根据文档:

[handleSubmit] 像 validate 一样调用验证并改变提供者的状态,只有在验证成功时才接受要运行的回调。

因此,要在验证出错的情况下运行回调,您必须使用ValidationObserver 中的ref 以编程方式触发验证。

您的开始 ValidationObserver 标记现在看起来像这样:

...
<ValidationObserver tag='div' class='bg-white pt-6 pb-6 mb-4' ref='form'>
...

您的开头form 标签现在应该是这样的:

...
<form
  @submit.prevent='onSubmit'
  class='mx-auto rounded-lg overflow-hidden pt-6 pb-6 space-y-10'
  :class="{'is-loading' : isLoading}"
>
...

你的onSubmit 方法应该是这样的:

onSubmit () {
  this.$refs.form.validate().then(success => {
    if (!success) {
      // run your error code here
    }

    alert('Form has been submitted!');

  });
}

除了这种编程方法之外,没有与handleSubmit 等效的方法可以在无效表单提交后运行回调函数。

查看文档以获取有关 programmatic access with $refs 的更多信息。

【讨论】:

    猜你喜欢
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2019-08-13
    • 2021-12-29
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    相关资源
    最近更新 更多