Veevalidate:在POST请求之前验证表单?

时间:2019-05-13 14:54:57

标签: vue.js vee-validate buefy

我正在使用VeevalidateBuefy在POST请求之前验证表单。我能够正确验证表单,但是POST请求方法会在验证之前运行。

我对如何按顺序调用方法感到困惑:

  1. 验证表格
  2. POST请求

代码和框:https://codesandbox.io/s/mj1vy2vq0j

代码概述

<b-modal>
  <form @submit.prevent="validateBeforeSubmit">
    ...
    ...
    <button type="submit" class="button is-primary" @click="postItem()">Submit</button>
    <button type="button" class="button" @click="isAddModalActive=false">Cancel</button>
  </form>
</b-modal>

<script>

...

methods: {
  validateBeforeSubmit() {
    this.$validator.validateAll().then(result => {
      if (result) {
        this.$toast.open({
          message: "Form is valid!",
          type: "is-success",
          position: "is-bottom"
        });
      }
      this.$toast.open({
        message: "Form is not valid! Please check the fields.",
        type: "is-danger",
        position: "is-bottom"
      });
    });
  },
  postItem() {
    alert("postItem function was called");
  }
}
</script>

1 个答案:

答案 0 :(得分:1)

您可以在validateBeforeSubmite()函数中调用您的Submit函数

methods: {
  validateBeforeSubmit() {
    this.$validator.validateAll().then(result => {
      if (result) {
        this.$toast.open({
          message: "Form is valid!",
          type: "is-success",
          position: "is-bottom"
        });
       this.postItem()// call your post function here and remove from @click in your submit button
      }
      this.$toast.open({
        message: "Form is not valid! Please check the fields.",
        type: "is-danger",
        position: "is-bottom"
      });
    });
  },
  postItem() {
    alert("postItem function was called");
  }
}