Categories
Vue Answers

How to get form data on submit with Vue.js?

Spread the love

Sometimes, we want to get form data on submit with Vue.js.

In this article, we’ll look at how to get form data on submit with Vue.js.

How to get form data on submit with Vue.js?

To get form data on submit with Vue.js, we can get them from the submit event object.

For instance, we write

<template>
  <div id="app">
    ...
    <form @submit.prevent="getFormValues">
      <input type="text" name="name" />
    </form>

    ...
  </div>
</template>

<script>
export default {
  //...
  methods: {
    getFormValues(submitEvent) {
      this.name = submitEvent.target.elements.name.value;
    },
  },
  //...
};
</script>

to set @submit.prevent to getFormValues to use getFormValues as the submit event handler.

Then in getFormValues we get the submitEvent object and then get the value of the input with the name attribute set to name with

submitEvent.target.elements.name.value;

submitEvent.target is the form element since we set @submit.prevent to getFormValues.

Conclusion

To get form data on submit with Vue.js, we can get them from the submit event object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *