I\'m using Vue in my application and I would like to know how to submit a form but avoid redirection. According to the official Vue doc it can be achieved in the following w
onSubmit
should be a function within your methods
property on the vue instance. I.e
methods: {
onSubmit () {
// DO Something
}
}
Then as the docs say, using <form v-on:submit.prevent="onSubmit"></form>
is correct. I use this in my app.
See the example below. The message will change once the button is clicked without a page refresh.
var vm = new Vue({
el: '#app',
data () {
return {
test: 'BEFORE SUBMIT'
}
},
methods: {
onSubmit () {
this.test = 'AFTER SUBMIT'
}
}
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
{{test}}
<form v-on:submit.prevent="onSubmit">
<button>Submit!</button>
</form>
</div>
Try @submit.prevent="myFunction()"
, and your button
could instead be <input type="submit" value="Submit"/>
. The submit
type will trigger the form to submit, and the submit.prevent
will prevent the default submit behavior and execute myFunction
as desired.
This has the additional benefit of triggering form validation for required input fields!
Just use @submit.prevent
(without any equal signs).
Then, define @click="doAction()"
on the button.