Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

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>

Answer №1

When working with forms, you can utilize the reactive() function as shown below:

const form = reactive({
    surname: "",
    name: "",
    company: "",
    phone: "",
    email: "",
    msg: "",
});

There's no need to create a separate FormData() instance. Simply pass the reactive form directly to the endpoint like this:

const response = await axios.post(apiEndpoint, form, {
    headers: {
      "Content-Type": "application/json",
    },
});

console.log(response)

To enable v-model support for reactive(), you just need to add this in your input element:

<input v-model="form.name" />

Additional Information

If you want to specify the object type, you can achieve it like so:

const form = reactive<Interface>({
    surname: "",
    name: "",
    ...
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Module '@tanstack/react-table' cannot be located even though it has been successfully installed

Currently, I am tackling a TypeScript React project and encountering an issue while attempting to import ColumnDef from @tanstack/react-table in my columns.tsx file. import { ColumnDef } from "@tanstack/react-table"; export type Payment = { id ...

Enhance your webpage with our jQuery plugin that allows you to easily make Ajax

I am currently working on developing a custom jquery plugin. One of the functions within this plugin requires an ajax-call to be made. However, I want to ensure that the function remains chainable, meaning that the ajax-call should only happen after a re ...

Why is the value in my React Redux state not updating as expected?

I recently started learning react js as a beginner. To practice, I created a crud app and integrated firebase for authentication. However, I'm facing an issue where I'm not able to retrieve the updated value. Index.jsx At line 11, I'm stru ...

Reload the MEN stack webpage without the need to reload the entire page

I am in the process of developing a data analytics dashboard using the MEN stack (MongoDB, Express.js, Node.js). I have successfully implemented functionality to display real-time data that refreshes every 5 seconds without the need to reload the entire ...

Travis-CI build encountering errors, however, local tests and builds run smoothly

I'm encountering difficulties getting my unit test to pass with Travis. When running the tests locally, I don't see any errors (unit/e2e)... If you'd like to see the log file, it can be found here in the Travis build log There are numerous ...

effectively showcasing information in a datatable by converting JSON data into objects

I am looking for a way to display balance information in datatables, but I have not been able to find a solution yet. <!DOCTYPE html> <html lang="en"> <head> <title>Comment</title> <meta charset="u ...

Utilize .map function to format a date string and generate a table

I am currently utilizing .map along with React in order to generate a table using a coupons object. My goal is to format a date string into the "mm/dd/yyyy" format, with coupon.starts_at typically being set as coupon.starts_at = "2013-08-03T02:00:00Z" I h ...

Building on the powerful foundation of Laravel 5.3, we have crafted a seamless Vue 2.0 form for

I'm encountering difficulties with user authentication using Vue 2.0. Within my Vue application, I have a form where users input their information and submit it via POST to a Laravel endpoint. Once the user is created in the UserController method wi ...

Is it feasible to incorporate a multi-level navigation menu into the "NavItem" component using MaterialUI with TypeScript?

Instructions for creating a multi-level navigation menu using MaterialUI and TypeScript: To the existing '/questions' section, it is desired to include the following 2 navigation menus: /questions/Tags /questions/Users This should resemble the ...

Does the gltf loader in three.js have compatibility issues with Internet Explorer 11?

Despite the claims on the official website that gltf files should load in three.js scenes using IE11, I have been experiencing issues with the loader. Even the examples provided by three.js fail to work on Internet Explorer when it comes to loading gltf fi ...

Try utilizing a distinct value for searching compared to the one that is shown in Material UI's Autocomplete feature for React in JavaScript

I'm currently utilizing the <AutoComplete /> component offered by Material UI. It prescribes the following organization for the options const options = [ { label: 'The Godfather', id: 1 }, { label: 'Pulp Fiction', id: 2 } ...

Issues with the Node Package Manager's watch command functionality

Having installed the frontend dependency in my Vue.js project, I attempted to run the command npm run watch. I updated the scripts section in package.json as shown below- "scripts": { "dev": "npm run development", &qu ...

What causes the variation in typing behavior between specifying props directly on a component versus nesting them inside another prop?

Understanding the next component might be a bit tricky, so let's delve into it (Check playground): type Props<T> = { initValue: T, process: (value: T) => T } export const Input = <T,>({ initValue, process, }: Props<T>): ...

Utilize AJAX to connect to a remote domain from an extension

I am currently working on creating a Chrome extension that will utilize AJAX to fetch data from a specific webpage and then generate notifications based on the content of that page. The webpage I am targeting is a ticketing system, and my goal is to deter ...

Searching for single and double quotes within a string using RegExp in JavaScript

I have encountered an issue while searching for a substring within a string using the code below: mystring.search(new RegExp(substring, 'i')) The reason I am utilizing new RegExp is to perform a case-insensitive search. However, when the string ...

Convert JSON data into an HTML table using JavaScript without displaying the final result

I need help troubleshooting my JavaScript code that is supposed to populate an HTML table with data from a JSON file. However, the table remains empty and I can't figure out why. Sample JSON Data [{"User_Name":"John Doe","score":"10","team":"1"}, { ...

What is the optimal value for the variable x in this scenario?

What is the correct value for X to make this condition valid? // Your code goes here if (x == 1 && x === 2) { console.log('Success!'); } ...

Please enter data into the input fields provided in the text

Below is the code where Google transliteration is used for typing in Indian language in a text field. There are two routes with different page IDs. Initially, the transliteration works fine on the default page. However, when changing routes, an error occur ...

Error in Vue.js: Trying to access properties of an undefined object

My understanding of vue.js is limited, but based on what I know, this code should work. However, when attempting to access the variable in the data property, it seems unable to locate it. data: function() { return { id: 0, clients: [] ...

After the request.send() function is called, the request is not properly submitted and the page automatically redirects

I'm currently working on a basic ajax comment form that includes a textarea and a yes/no radio button. If the user selects 'yes', their comments are posted and then they are redirected to a new page. If the user selects 'no', th ...