One of the common tasks when working with HTML form is to stop it from reloading when customers clicks the submit button. In this article, we will look at how to prevent this default behaviour of HTML forms in Vue.

We will start by creating a simple HTML form.

<form>
  <div>
    <label for="name">Name: </label>
    <input id="name" type="text" />
    <input id="submit" type="submit" />
  </div>
</form>

preventDefault()-vue

When we click on the submit button, the page reloads. Let’s see how we can prevent this from happening in Vue.

We can listen to the submit event using v-on:submit which calls a method onSubmit().

<form v-on:submit="onSubmit()">
  <div>
    <label for="name">Name: </label>
    <input id="name" type="text" />
    <input id="submit" type="submit" />
  </div>
</form>

In the onSubmit() method, we can call the preventDefault() function on the event object.

onSubmit(e) {
  e.preventDefault();
}

This will stop the page from reloading.

So, the entire code will look like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <title>Vue.Js</title>
  </head>

  <body>
    <div id="app">
      <form v-on:submit="onSubmit">
        <div>
          <label for="name">Name: </label>
          <input id="name" type="text" />
          <input id="submit" type="submit" />
        </div>
      </form>
    </div>
  </body>

  <script>
    const { createApp } = Vue;

    createApp({
      methods: {
        onSubmit(e) {
          e.preventDefault();
        },
      },
    }).mount("#app");
  </script>
</html>

Using event modifier - prevent

In Vue we can attach a modifier called .prevent after the v-on directive to prevent the default behaviour of forms. This makes it easy and avoids the need for writing the logic e.preventDefault() in the event handler.

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

The entire code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <title>Vue.Js</title>
  </head>

  <body>
    <div id="app">
      <form v-on:submit.prevent="onSubmit">
        <div>
          <label for="name">Name: </label>
          <input id="name" type="text" />
          <input id="submit" type="submit" />
        </div>
      </form>
    </div>
  </body>

  <script>
    const { createApp } = Vue;

    createApp({
      methods: {
        onSubmit(e) {
          // e.preventDefault(); ❌ not required
        },
      },
    }).mount("#app");
  </script>
</html>