To call preventDefault()
on form submission with Vue.js, we can use the .prevent
event modifier in the form submission event handler.
This modifier tells Vue.js to automatically call event.preventDefault()
when handling the event.
To do this we write:
<template>
<form @submit.prevent="submitForm">
<input type="text" v-model="username" placeholder="Username">
<input type="password" v-model="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
</template>
<script>
export default {
data() {
return {
username: '',
password: ''
};
},
methods: {
submitForm(event) {
// Our form submission logic here
}
}
};
</script>
The @submit.prevent
directive listens for the submit
event on the form and calls event.preventDefault()
internally to prevent the default form submission behavior.
When the form is submitted, the submitForm
method is called.
Inside the submitForm
method, we can implement our custom form submission logic.
Vue.js automatically passes the event
object to the event handler, so we can access it and call event.preventDefault()
if needed.
Using @submit.prevent
is a convenient way to prevent the default form submission behavior while handling form submissions with Vue.js.