I have a Form, with some fields. Get there value with v-model to some ref objects. To get my data in my FormData object, I need the name and the value of the ref objects.. I don't want formData.append() to repeat
I can't get the name of the ref objects. Is this possible?
- put the objects in an array.
- iterate trough the array (foreach) and append the data to my FormData object.
"formdata.append("nameOfRefObject", refObject.value)"
I've tryed
formData.append(Object.keys(key)[0], key.value);
Here is the Code:
<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, token];
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>
CodePudding user response:
To use forms you can use the reactive()
function, something like this:
const form = reactive({
surname: "",
name: "",
company: "",
phone: "",
email: "",
msg: "",
});
And you don't need to create a FormData()
instance. You can pass directly the reactive form to the ep, something like this:
const response = await axios.post(apiEndpoint, form, {
headers: {
"Content-Type": "application/json",
},
});
console.log(response)
If you want the v-model support for reactive()
function, it's as simple as doing this in your input:
<input v-model="form.name" />
Extra comments
If you want type the object, you can do this:
const form = reactive<Interface>({
surname: "",
name: "",
...
});