How to submit form to array and clear inputs in vue.js?

by darrion.kuhn , in category: Javascript , 5 months ago

How to submit form to array and clear inputs in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 5 months ago

@darrion.kuhn 

To submit a form to an array and clear the inputs in Vue.js, you can follow these steps:

  1. Create a data property in your Vue component that will hold the array of form submissions. For example:
1
2
3
4
5
6
7
data() {
  return {
    formSubmissions: [],
    name: '',
    email: ''
  }
}


  1. Create a method that will handle the form submission and push the form data to the formSubmissions array. This method should also clear the input fields after submitting the form. For example:
1
2
3
4
5
6
7
methods: {
  submitForm() {
    this.formSubmissions.push({ name: this.name, email: this.email });
    this.name = '';
    this.email = '';
  }
}


  1. In your template, bind the input fields to the data properties using v-model and add a submit button that calls the submitForm method when clicked. For example:
1
2
3
4
5
<form @submit.prevent="submitForm">
  <input type="text" v-model="name" placeholder="Name">
  <input type="email" v-model="email" placeholder="Email">
  <button type="submit">Submit</button>
</form>


  1. Display the form submissions in your template by looping through the formSubmissions array. For example:
1
2
3
4
5
6
<ul>
  <li v-for="submission in formSubmissions" :key="submission.email">
    <span>Name: {{ submission.name }}</span>
    <span>Email: {{ submission.email }}</span>
  </li>
</ul>


Now, when you fill out the form and submit it, the form data will be added to the formSubmissions array and the input fields will be cleared. The form submissions will also be displayed in a list below the form.