When utilizing the vue @submit directive, the FormData object may be found to be devoid

Encountering a unique edge case, I found a solution. When creating a form with Vue, I noticed that empty strings were being sent to the server. Upon investigation, it became apparent that the issue lies within the @submit directive. Interestingly, when utilizing form.addEventListener('submit'), the functionality works correctly, contrary to using @submit.

The workaround involves using the addEventListener method, raising questions about potential errors on my end or if this is a bug related to Vue's v-on directive.

For a runnable example, refer to: https://stackblitz.com/edit/web-platform-izreva?file=index.html

NOTE: Familiarity with the form data object and viewing it can be attained through:

for (const [key, value] of formData.entries()) {
  console.log(`${key}: ${value})
}

In the snippet below, uncommenting the code enables proper functionality with the addEventListener approach.

const form = document.querySelector('#test-form')

const app = Vue.createApp({
  name: 'test app',
  methods: {
    test(e) {
      e.preventDefault()
      console.log(e)

      const formData = new FormData(form)
      for (const [key, value] of formData.entries()) {
        console.log(`${key}: ${value}`)
      }
    }
  }
}).mount('#app-main')

// const form = document.querySelector('#test-form')
// form.addEventListener('submit', e => {
//   e.preventDefault()

//   const formData = new FormData(form)
//   for (const [key, value] of formData.entries()) {
//     console.log(`${key}: ${value}`)
//   }
// })
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Home</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="acdad9c9ec9f829e82989b">[email protected]</a>/dist/vue.global.js" defer></script>
  </head>
  <body>
    <h1>app</h1>
    <div id="app-main">
      <form @submit="test" id="test-form">
        <input type="text" name="foo">
        <button type="submit">submit</button>
      </form>
    </div>

    <script src="./index.js" defer></script>
  </body>
</html>

Answer №1

It seems like the issue lies in how Vue's CDN version interprets a template within existing HTML code.

Vue replaces each element with its compiled equivalent, which might be causing the problem you're experiencing.

The form element you initially captured is no longer the one triggering the submit event. To confirm this, you can compare form === e.target.

If you modify your code as shown below, it should function as intended:

const formData = new FormData(e.target);

In summary, it appears that your approach deviates from typical Vue practices, hence the unexpected hurdles you've encountered.

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

`Balance in structure`

Having trouble with CSS. I would like to make this form symmetrical. Buttons should be in one column, textfields in another, and the question mark should also have its own column. Apologies if the ticket structure is not perfect, this is only my second on ...

AngularJS encountered an error: The token '|' was unexpected and expected ':' instead

My HTML file contains a condition where certain fields need to be displayed automatically in landscape mode using filters. However, when I run the program, I encounter the following code: <tbody> <tr ng-repeat="ledger in vm.ledgers ...

Javascript promise failing to deliver

As a beginner in the world of JavaScript development, I am excited to be part of the stackoverflow community and have already gained valuable insights from reading various posts. Currently, I am facing an issue where I need to load a file, but due to its ...

Tips for Editing and Modifying Name and Area in a Database

I'm currently working with React to develop a full CRUD application, but I'm facing challenges in updating the names and areas of rooms within houses. Any suggestions or insights on how to achieve this would be greatly appreciated. Apologies for ...

Emulate an AngularJS ng-click action

My website has HTML code with three buttons: <button ng-click='showStats(player.data,0)'>Death Match</button> <button ng-click='showStats(player.data,1)'>Champions Rumble</button> <button ng-click='sho ...

Utilize Vue.js to easily upload images alongside form input fields

I have recently started a small project with Vue Js. I am trying to incorporate an upload file option in my contact form. Due to the numerous input text fields, I am using serialize for the form. However, I am facing issues with the append function. How ca ...

Throttle the asynchronous function to guarantee sequential execution

Is it possible to use lodash in a way that debounces an async function so it runs after a specified delay and only after the latest fired async function has finished? Consider this example: import _ from "lodash" const debouncedFunc = _.debounc ...

What might be causing the issue of not being able to access req.body using multer?

In my application built using vue, users have the ability to upload files along with some data to my node backend. Once the user submits the form, the following function is executed: methods: { buttonOK () { const formData = new FormData() ...

Tips for selecting specific types from a list using generic types in TypeScript

Can anyone assist me in creating a function that retrieves all instances of a specified type from a list of candidates, each of which is derived from a shared parent class? For example, I attempted the following code: class A { p ...

Using JSON input to add color to a d3 bullet chart

I am currently working with a D3 bullet chart example and trying to enhance it by incorporating different colors for the ranges directly into the JSON file. The link to the original example can be found here: . I need this customization because I require d ...

Using a JSON key as a parameter in a function

Would it be achievable to specify the key of an object as a function parameter? For instance, if I were to develop a filter function that could sort multiple map markers by marker.element.country or marker.element.population? This approach would allow me ...

Collapse or display div elements with jQuery - First close all other elements before opening the selected item

The Problem at Hand Currently, the script is expected to hide all elements with the "gallery-collapse" class and reveal the specific content based on the clicked link. However, sometimes multiple divs might appear simultaneously when switching between ite ...

Retrieve container for storing documents in JavaServer Pages

Previously, I created JSP and HTML code to upload a file from the hard disk into a database using <input type="file" name="upfile"> However, a dialog box with an "Open" button is displayed. What I am looking for is a "Save" button that will allow u ...

Dealing with onChange value in a date in reactjs is a common challenge that developers

I'm currently working on a basic date input component in React, but I've run into an issue when trying to change the value. Every time I update it, it always displays "1970-01-01". If anyone has any suggestions on how to fix this problem, I woul ...

A guide on handling POST response body parsing in NodeJS

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.get("/", function(req, res){ res.sendFile(__dirname + "/index.html"); }); app.post("/", function(r ...

Discover the steps for retrieving the <div> element using the swiper API

Link to my page: Click here Design reference: View design The design requires flexing the 2 arrow buttons, but these elements are missing in the code(source: autoplay swiper). How can I align them to the right-bottom corner? <div class="flex" ...

The result should display the top 5 application names based on the count property found within the ImageDetails object

data = { "ImageDetails": [ { "application": "unknownApp, "count": 107757, }, { "application": "app6", "count": 1900, }, { & ...

Ways to retrieve the output from an AJAX call

Today I'm developing a JavaScript function named "sendData". This function simplifies the process by eliminating the need to manually code an entire ajax statement. However, considering that it operates asynchronously, I found myself wondering how to ...

What are the benefits of incorporating 'i in array' into my personalized 'array.indexOf' function?

I've come across code like this multiple times: function customArrayIndexOf(item, array){ for (var i = 0, l = array.length; i < l; i++) { if (i in array && array[i] === item) return i; } return -1; } But I'm unsur ...

Combining property values based on a common property in an array of objects using JavaScript

I have a large array filled with various objects structured like: [ { "type": "bananas", "count": 15 }, { "type": "kiwis", "count": 20 }, { "type": "bananas", ...