codernoob6
codernoob6

Reputation: 71

prevent form default behavior in Vue.js

I'm building a Vue.js app with a form and I was wondering is there a way to prevent the HTML 5 forms default behavior using Vue.js built in .prevent? I have tried <form.prevent> and <form v-on:submit.prevent> but to no avail. Any help here would be great?

Upvotes: 6

Views: 11347

Answers (1)

ghybs
ghybs

Reputation: 53185

The v-on directive (shorthand @) is to bind a Vue instance method or a JS expression to an event:

Attaches an event listener to the element. […] The expression can be a method name, an inline statement, or omitted if there are modifiers present.

Therefore even if you do not specify a method or an expression / inline statement, your .prevent modifier should work in any case:

new Vue({
  el: '#app',
  methods: {
    formSubmit() {
      console.log('form submitted');
    },
  },
});
<script src="https://unpkg.com/vue@2"></script>

<div id="app">
  <form @submit.prevent>
    <span>Form WITH submit.prevent and no expression attached</span>
    <button type="submit">Submit form</button>
  </form>
  <form @submit.prevent="formSubmit">
    <span>Form WITH submit.prevent</span>
    <button type="submit">Submit form</button>
  </form>
  <form @submit="formSubmit">
    <span>Normal form without prevent</span>
    <button type="submit">Submit form</button>
  </form>
</div>

Upvotes: 12

Related Questions