[Vuejs]-How to abort vue.js method post if any required fields are null

0👍

Really you should wrap this in a form:

<form v-on:submit.prevent="postResults">

Then remove the click handler from the button.

Next, create a new method, we’ll call it validatesFields. Make it return a promise that either resolves or rejects based on validity:

validatesFields: function() {
  return new Promise(function(resolve, reject) {
    if (this.field.valid && this.other_field.valid&&) {
      return resolve()
    } else {
      return reject()
    }   
  })
}

Finally, observe this promise in your postResults function:

postResults: function () {
   this.validatesFields()
     .then(function(){
       this.$http.post('/Controller/Action/', {
          Endereco: this.endereco,
          Cidade: this.cidade,
          Estado: this.estado,
          CEP: this.cep,
          SEND: false
       }).then((response) => {
          console.log(response.data);
          console.log(response.data.worked);
          if (response.data.worked) {
            console.log("DADOS ADICIONADOS!");
          }
        });
     }).error(function(){
       // field validation failed, do something here
     })

    }

Leave a comment