I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects.
Unfortunately, I am struggling to retrieve the name of the ref objects. Is there a way to do this?
- One approach could be to store the ref objects in an array.
- Then, iterate through the array (using forEach) and append the data to the FormData object.
"formData.append("nameOfRefObject", refObject.value)"
I attempted the following:
formData.append(Object.keys(key)[0], key.value);
https://i.stack.imgur.com/1utwK.png
Below is the code snippet:
<script setup lang="ts">
const surname = ref("");
const name = ref("");
const company = ref("");
const phone = ref("");
const email = ref("");
const msg = ref("");
async function submitForm(submit: Event) {
const helperArr = [surname, name, company, phone, email, msg];
const formData = new FormData();
helperArr.forEach((key) => {
formData.append(Object.keys(key)[0], key.value);
});
await axios.post(apiEndpoint, formData, {
headers: {
"Content-Type": "application/json",
},
}).then((res) => {
console.log(res);
});
}
</script>