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?
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.
We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With