How to reset a form in Vue.js?

by reagan_barton , in category: JavaScript , 2 years ago

How to reset a form in Vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@reagan_barton You can use reset() method to clear or reset a form in Vue.js or see also an example how to set it back to initial value, code as example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script setup>
import { ref } from 'vue'

const username = ref('test')
const contactForm = ref(null);

function submitForm() {
  console.log('form is submitted');
  console.log(`Username: ${username.value}`);
}
  
function clearForm() {
  // Reset form
  contactForm.value.reset()
  // or set back to initial value
  // username.value = 'test'; 
}
</script>

<template>
  <h1>Contact us</h1>
  <form ref="contactForm" @submit="submitForm">
      <input type="text" name="username" v-model="username">
  </form>
  <button @click="clearForm">Reset Form</button>
</template>
by audrey.hodkiewicz , a year ago

@reagan_barton 

To reset a form in Vue.js, you can do the following:

  1. Create a data property to hold the default or initial values of the form fields:
1
2
3
4
5
6
7
8
9
data() {
  return {
    formFields: {
      name: '',
      email: '',
      message: ''
    }
  }
}


  1. Bind the formFields object to the form's input fields using v-model:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<div>
  <label for="name">Name:</label>
  <input type="text" id="name" v-model="formFields.name">
</div>
<div>
  <label for="email">Email:</label>
  <input type="email" id="email" v-model="formFields.email">
</div>
<div>
  <label for="message">Message:</label>
  <textarea id="message" v-model="formFields.message"></textarea>
</div>


  1. Create a method to reset the form by assigning the initial values to the formFields object:
1
2
3
4
5
6
7
8
9
methods: {
  resetForm() {
    this.formFields = {
      name: '',
      email: '',
      message: ''
    }
  }
}


  1. Add a reset button to the form and call the resetForm method on click:
1
<button type="button" @click="resetForm">Reset</button>


Now, when the user clicks the reset button, the resetForm method will be called and the formFields object will be assigned the initial values, effectively resetting the form.