Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent form default behavior in Vue.js

Tags:

forms

vuejs2

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?

like image 413
codernoob6 Avatar asked Aug 01 '18 21:08

codernoob6


People also ask

How does JavaScript prevent a form from being submitted?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.

How do I stop a form from submitting in jquery?

We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.

How do you clear a form on Vue?

In vue. js, we use the v-model directive to create a two-way data binding between the input field and vue data property, so that we can clear an input field value by setting the empty string (" ") to the data property.

How do I stop form submit in react?

Use the preventDefault() method on the event object to prevent form submission in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.


1 Answers

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>
like image 192
ghybs Avatar answered Sep 25 '22 16:09

ghybs