Bill
Bill

Reputation: 365

Using event modifier .prevent in Vue to submit form without redirection

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 way:

<!-- the submit event will no longer reload the page -->
<form v-on:submit.prevent="onSubmit"></form>

Here is my part of my form:

<form class="myForm" action="/page" method="post" @submit.prevent="onSubmit">
    <input name="email" type="email" placeholder="e-mail" v-model="email">
    <button @click="myFunction()">

It sorta works in the sense that the page is no longer redirected but I get an error saying that onSubmit method is not defined. So What I don't understand is how I should define it. On the other hand I could just write @submit@prevent but as far as I understand it completely prevents submission and that's not what I'm looking for. Is there a proper way to do this without ajax, axios and that sort of technologies? What I want is myFunction to execute and form to submit but I would want to avoid redirection.

Upvotes: 18

Views: 66693

Answers (5)

putaoshu
putaoshu

Reputation: 11

Try to change <button @click="myFunction()"> to <button type="button" @click="myFunction()">

Upvotes: 1

Rxhack com
Rxhack com

Reputation: 156

<form @submit.prevent="saveData()" method="post"> <!-- Add all the input filed --> <button type="submit"> Save </button> </form>

This will avoid redirection of the form also we can validate input fields.

Upvotes: 2

Exis Zhang
Exis Zhang

Reputation: 560

Just use @submit.prevent (without any equal signs).

Then, define @click="doAction()" on the button.

Upvotes: 24

webnoob
webnoob

Reputation: 15934

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>

Upvotes: 47

B. Fleming
B. Fleming

Reputation: 7220

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!

Upvotes: 4

Related Questions