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

后端 未结 3 1495
日久生厌
日久生厌 2021-01-05 01:33

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

相关标签:
3条回答
  • 2021-01-05 01:57

    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>

    0 讨论(0)
  • 2021-01-05 01:58

    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!

    0 讨论(0)
  • 2021-01-05 02:08

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

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

    0 讨论(0)
提交回复
热议问题