DEV Community

Cover image for Prevent Form Submission in Vue.js
Raja Tamil
Raja Tamil

Posted on

Prevent Form Submission in 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>


Enter fullscreen mode Exit fullscreen mode


form {
  width:400px;
  margin:20px auto;
}


Enter fullscreen mode Exit fullscreen mode

alt text

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>


Enter fullscreen mode Exit fullscreen mode

Then, declare the signInButtonPressed function inside the methods object.



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


Enter fullscreen mode Exit fullscreen mode

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.

Continue Reading...

Top comments (0)