I want to do a classic form submission from my Vue page, from a method. I don't want to use an <input type="submit">
. How do I reference the form element in the page from my method? Surely I don't have to do document.getElementById()
?
markup
<div id="vueRoot">
<form>
<input name="vitalInformation" v-model="store.vital">
<a href="#" v-on:click="submit">SUBMIT</a>
</form>
</div>
code
var store = {vital:''};
vm = new Vue({
el : "#vueRoot",
data : {store : store},
methods : {
submit : function(){
//I'm ready, how do I do it ??
}
}
});
jsfiddle
new Vue({ el: 'body', methods: { submit: function(e) { var form = document. getElementById('form'); var formData = new FormData(form); axios. post('/someUrl', formData) . then((response) => { // success callback }, (response) => { // error callback }); } } });
Simply use v-bind like :ref="'element' + result.id" or ref="`element${result.id}`" .
Get input value using ref The v-model is the preferred way of accessing the input value in Vue. However, we can also make use 'ref' attribute to get the input element's value. The ref attribute can be used on any DOM element and $refs object is used to get that reference element's content.
The answer would be: ref
: https://v2.vuejs.org/v2/api/#ref
<div id="vueRoot">
<form ref="form">
<input name="vitalInformation" v-model="store.vital">
<a href="#" v-on:click="submit">SUBMIT</a>
</form>
</div>
var store = {vital:''};
vm = new Vue({
el : "#vueRoot",
data : {store : store},
methods : {
submit : function(){
this.$refs.form.$el.submit()
}
}
});
Another option is trigger the event click()
.
<button ref="submit" style="display:none;">Submit</button>
In your function call it as follows:
this.$refs.submit.click();
Sorry for the late reply, but I am confused why you need ref
when submitting a form.
data: function(){
return {
name: "",
price: "",
}
},
methods: {
addProduct(e){
e.preventDefault() // Prevent page from reloading.
// console.log(this.name, this.price);
}
}
<form v-on:submit="addProduct">
<input type="text" v-model="name" placeholder="Product Name" >
<input type="number" v-model="price" placeholder="Price">
<button type="submit">Add</button>
</form>
From above answers I used following statements
this.$refs.form.submit()
this.$refs.submit.click();
both throw following error
TypeError: Cannot read property '$refs' of null
I'm able to fix this issue by storing $refs in a variable then access the relevant method
if you want to use ref for form submit event
const form = this.$refs.formRef
form.submit()
if you want to use ref for other element's event like click
const btn = this.$refs.btnRef
btn.click()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With