Prevent Form Submission in Vue.js

Vue.js

In this article, I’m going to cover two different ways on how to prevent default form submission behaviour using vue.js.

Let’s say you have a sign-up form that you do not want to submit to the server directly.

As you know, the default behaviour of the form element is to send the form input data via GET request when the submit button is pressed.

<form class="ui large form">
  <div class="field">
    <div class="ui left icon input">
      <i class="user icon"></i>
      <input type="text" placeholder="Username or Email"/>
    </div>
  </div>
  <div class="field">
    <div class="ui left icon input">
      <i class="lock icon"></i>
      <input type="password" placeholder="Password"/>
    </div>
  </div>
  <button class="ui fluid pink button big" >SIGN IN</button>
</form>
form {
  width:400px;
  margin:20px auto;
}

To prevent that, what we want is to handle the form submission via an AJAX call of some sort.

There are two main ways you can prevent form submission in vue.js.

Invoke preventDefault Method

Attach a click event with a callback function signInButtonPressed to the submit button.

<button class="ui fluid pink button big" @click="signInButtonPressed">SIGN IN</button>

Then, declare the signInButtonPressed function inside the methods object.

methods: {
 signInButtonPressed() {
  console.log("sign in button is pressed");
 }
}

When you hit the sign in button at this stage, you can see the message quickly in the browser console and then it disappears as the page gets reloaded.

Also notice the question (?) mark added to the URL that indicates the form is trying to send data via GET request.

You can add a name attribute to each input field, which is inside the form element, if you want see the input values in the URL.

To stop this behaviour, all we have to do is to call the preventDefault() method on the click event object.

methods: {
  signInButtonPressed(e) {
    console.log("Sign In Button Pressed");
    e.preventDefault();
  }
}

Recommended
Vue.js & Semantic UI: Design Cool Sign Up Form Faster

Submit Event with Prevent Modifier

The other way we can achieve preventing the default form submission behaviour is by attaching a submit event with the prevent modifier to the starting form tag in the template.

This will prevent the page from reloading when the submit button is pressed as well.

Also set a callback function called signInButtonPressed to it.

<form class="ui large form" @submit.prevent="signInButtonPressed">
....
</form>

This way we do not have to attach a click event to the sign in button.

<button class="ui fluid pink button big">SIGN IN</button>

When the sign in button is pressed the callback function which is attached to the submit event will be fired and we do not have to invoke the preventDefault() method as well.

methods: {
  signUpButtonPressed() {
    console.log("Sign In Button Pressed");
  }
}

There you have it!

Recommended
Vue JS Form Validation Using Options AP