Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defer form submission to a method?

Tags:

vue.js

vuejs2

I have a form:

<form id="myForm" @submit.prevent="doSomething()">...</form>

In doSomething() I make a check and if true, I want to submit the form. How can I submit the form after the check?

like image 573
panthro Avatar asked Dec 23 '22 20:12

panthro


1 Answers

Add a ref attribute to the form

You can add a ref attribute to the form element. Then, in the doSomething method, you can submit the form via this.$refs.form.submit().

Template:

<form id="myForm" ref="form" @submit.prevent="doSomething()">...</form>

Vue component methods:

doSomething() {
  // do something
  
  this.$refs.form.submit();
}

For more info on refs: https://v2.vuejs.org/v2/api/#ref

Pass the event object to the method

You can also pass the event object to doSomething by adding the $event param. This gives the method a reference to the target element:

Template:

<form id="myForm" @submit.prevent="doSomething($event)">...</form>

Vue component methods:

doSomething(e) {
  // do something
  
  e.target.submit();
}
like image 103
thanksd Avatar answered Jan 05 '23 20:01

thanksd