Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset a form in Vue 3

This is my form and I want to clear the values after submitting the form,

<form @submit.prevent="addNewUser" ref="newUserForm">

<script setup>
 import { ref } from "vue";

 //Reference to new user form
const newUserForm = ref();

//New user form
const userForm = reactive({
    id: "",
    name: "",
    email: "",
    telephone: "",
    address: "",
});

const addNewUser = async () => {
   ...
   newUserForm.reset();
}
</script>

This is the way I tried, but this is not working. Am I doing anything wrong here? Really appreciate your help. Thanks

like image 748
Mishen Thakshana Avatar asked Oct 29 '25 22:10

Mishen Thakshana


1 Answers

This is done in a generic way that isn't specific to forms.

Since initial dataset should exist in order to be assigned at some point, there may be factory function that provides it:

const getInitialFormData = () => ({ id: "", ... });

const userForm = reactive(getInitialFormData());

const resetUserForm = () => Object.assign(userForm, getInitialFormData());

This way the state is guaranteed to reset even if userForm object becomes nested at some point.

like image 191
Estus Flask Avatar answered Oct 31 '25 13:10

Estus Flask