Sometimes, we want to reference the form element when we submit a form in Vue.js.
In this article, we’ll look at how to reference the form element when we submit a form in Vue.js.
How to reference the form element when we submit a form in Vue.js?
To reference the form element when we submit a form in Vue.js, we can use a ref.
For instance, we write
<template>
<div>
<form ref="form" @submit.prevent="submit">
<input v-model="store.vital" />
<button type="submit">Submit</button>
</form>
</div>
</template>
<script>
//...
export default {
//...
methods: {
submit() {
this.$refs.form.$el.submit();
},
},
//...
};
</script>
to add a form and we assign the form
ref to it.
And we make the submit
method run when we submit the form with @submit.prevent="submit"
.
The prevent
modifier calls event.preventDefault
to prevent the default server side submission behavior.
In submit
, we get the form element with this.$refs.form.$el
.
Conclusion
To reference the form element when we submit a form in Vue.js, we can use a ref.