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

Dynamic HTML text colors that change rapidly

I have an interesting question to ask... Would it be possible to create text that switches between two colors every second? For example, could the text flash back and forth between red and grey? I don't mean changing the background color, I mean act ...

The manipulation of the DOM is not possible within the AJAX success function

I'm curious about the issue I am facing with changing the 'this' element on AJAX success. Despite my efforts to switch classes and add a new data attribute to the anchor tag in ajax success, it doesn't seem to be working. Interestingly, ...

C# web service is unable to return a specific value

I attempted to use a basic web service (just to test if the value will populate in the JavaScript code). I experimented with a very simple snippet, but it kept returning 'undefined'. Can you offer some guidance? I have tried several solutions wit ...

Having trouble passing a JavaScript variable through AJAX requests

In this particular script, I am encountering an issue where the variable "encrypted" is expected to be sent via ajax to upload.php, however I am unable to achieve this. Oddly enough, if I substitute the "encrypted" variable with another variable in the a ...

Tips for testing views in ember.js using unit tests

We are currently delving into the world of Ember.js. Our development process is completely test-driven, and we aim to apply the same methodology to Ember.js. Having prior experience in test-driven development with Backbone.js apps using Jasmine or Mocha/Ch ...

Comparing TypeScript and C++ in terms of defining class reference member variables

class B; class A { A(B b_) : b{b_} {} B &b; }; In C++, it is possible to have a reference member variable like 'b' in class A. Can the same be achieved in TypeScript? Alternatively, is there a specific method to accomplish this in ...

Is it possible to identify unauthorized utilization of web APIs within TypeScript?

Recently, I encountered an issue while using the URLSearchParams.size in my code. To my surprise, it didn't work on Safari as expected. Checking MDN's browser compatibility table revealed that Safari version 16.6 does not support this feature, un ...

The Art of JavaScript Module Patterns in Image Sliders

I'm diving into the world of JavaScript and decided to try my hand at creating an image slider. I managed to put together a basic version by following a couple of tutorials, and although it's working fine, I want to move it to an external js file ...

Sending JSON Data with Javascript Post Request

I've been attempting to send a JSON payload via a JavaScript script, but my webhooks don't seem to recognize the payload no matter what I try. Here is the code that I compiled from various online resources: let xhr = new XMLHttpRequest(); ...

Unable to locate the module '@vitejs/plugin-react' or its associated type

After creating the project with npm create vite@latest and selecting ts-react, everything seemed to work fine when I ran npm run dev. However, in my vs code editor, I encountered the error message "Cannot find module '@vitejs/plugin-react' or its ...

What are the steps for implementing a heatmap in Vue Highcharts?

Struggling with error 17 while attempting to use a heatmap chart type in vue-highcharts. I've searched online and it appears that importing and correctly using it may solve the issue. Can someone guide me through this process as there seems to be no d ...

Issues with the audio on ExpressJS video streaming can be quite vexing

After multiple attempts to run an ExpressJS web server that serves videos from my filesystem, I've encountered a frustrating issue. Whenever a video is played, there are constant popping sounds and eventually the audio cuts out completely after 3-10 m ...

Creating an easy-to-update catalog utilizing an external file: A step-by-step guide

I am looking to create a product catalog with 1-4 products in a row, each displayed in a box with details and prices. I would like to be able to generate the catalog easily using an XML/CSV file that can be updated. Can anyone provide guidance on how to ac ...

Is there a reason why the Chrome browser doesn't trigger a popstate event when using the back

JavaScript: $(document).ready(function() { window.history.replaceState({some JSON}, "tittle", aHref); $(window).bind("popstate", function(){ alert("hello~"); }); }); Upon the initial loading of the www.example.com page, the above JavaScript code is ex ...

Retrieve a specific element from an array list

Hey everyone, I'm facing a problem in my application where I need to extract a specific value from my array and display it in a table for users to see. Check out the code snippet below: Here's my mock data: { "Data": "2020-0 ...

Having trouble with bootstrap carousel malfunctioning on Firefox browser?

I'm experiencing an issue with the carousel slider on my website. It seems to only be working in Chrome and not in Mozilla Firefox. You can view the live site at: Below is the code I have used for the carousel: <header id="myCarousel" class="car ...

Click function for mat-step event handler

Is it feasible to create a click event for the mat-step button? I want to be able to add a (click) event for each mat-step button that triggers a method. Essentially, I am looking to make the mat-step button function like a regular button. You can find mo ...

Creating HTML elements with dynamic `routerLink` attributes in Angular 2

I have a model that references itself, as shown below. export class Entity { constructor(public id: number,public name: string,public children: Entity[]) { } } My goal is to create a tree list where each item has a routerlink. To achieve this, I ...

Am I on the right track in my understanding of how document and viewport relate to mouse position in JavaScript?

After reviewing responses from a previous inquiry, it is evident that both pertain to the x and y coordinates of mouse positions. In relation to the document and In relation to the viewport. I have delved into an article on QuirksMode, yet I feel ther ...

Tips for bringing in an npm package in JavaScript stimulus

Looking to utilize the imageToZ64() function within the zpl-image module. After installing it with: npm install zpl-image I attempted importing it using: import './../../../node_modules/zpl-image'; However, when trying to use the function like ...