Vue form component triggers the submit event twice

In my current project, I am utilizing the most recent version of Vue 3 without any additional vendors. After experiencing a setback in which I invested several hours attempting to uncover why my form component was triggering the submit event twice, I am left wondering if this is a bug or an anticipated behavior.

When listening for @submit on your form and subsequently $emit('submit') to enable listening to this event on the parent component, you will find that the event fires twice.

For a visual demonstration, please refer to the following pen: https://codepen.io/rekam/pen/dyeqxyy

Revised app logic goes here...

Although I can manage with specifying a distinct name for my submit event, I am curious as to why this issue occurs and whether it is intentional.

UPDATE

Upon further exploration, I discovered that enclosing the form tag within a div eliminates the second submit event. To replicate the scenario where the submit event occurs twice, you need:

  1. Your form serving as the top-level DOM element in your component
  2. Emitting an event named "submit"

Answer №1

There is no need to include the event @submit.prevent.stop="onSubmit" in your child component because it will be automatically inherited from the parent component.

template: `
    <form>
      <input type="text" />
      <input type="submit" value="in component" />
    </form>
  `,

template: `
    <div>
      <TestForm event-name="submit" @submit.prevent="() => onSubmit('with event name [submit]')" />
      <TestForm event-name="other" @submit.prevent="() => onSubmit('with event name [other]')" />
      <blockquote>
        <p v-for="(log, i) in logs" :key="i">{{ log }}</p>
      </blockquote>
      <input type="button" value="clear" @click="logs = []" />
    </div>
  `,

https://codepen.io/keyXpert/pen/dyegYQB

Answer №2

By triggering the submit action twice - once with a custom event listener created through 'emit', and another one with '@submit' added to your form tag, you are duplicating the process unnecessarily. It is advisable to choose either of these methods to efficiently submit your form.

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

Unveiling the secret to accessing properties using v-if within a custom component template relocation

I'm currently working on an application that reveals a hidden div when the text "Create Test" is clicked. Everything works well when the code isn't placed inside the template of a component. This seems strange to me, what could be causing this is ...

Click on a new tab to enable printing options for the page

I am looking to enhance the print page functionality on my website. Currently, when the print icon in the footer is clicked, it opens the printer dialog box directly. I would like to change this behavior so that when the Print icon is clicked, the contents ...

Passing the value of an Angular component to a different component

I have a menu in my application that uses IDs to route content, and I also have a detailed view where the content should be displayed based on those same IDs. Currently, I am trying to display objects by their ID when a button is clicked. However, I' ...

Similar to session_start() and $_SESSION in Node.js/Express

I'm on a quest to discover the equivalent of session_start() and $_SESSION in Node.js/Express so I can store the current user's id in the session. Most tutorials and videos recommend using express-session, but I've come across a warning: ...

Tips for integrating AsyncGenerators with Kotlin/JS

I am currently exploring the use of IPFS with Kotlin/JS, but my issue is not limited to that specific context. The functions ipfs.cat() and ipfs.get() return an AsyncGenerator, and I am uncertain about how to properly iterate over it using Kotlin (I am als ...

Challenges encountered when passing objects with Angular 2 promises

I am encountering a problem when using a promise to retrieve a Degree object in Angular 2. The initial return statement (not commented out) in degree.service functions correctly when paired with the uncommented implementation of getDegree() in build.compon ...

JavaScript - Combine objects by summing values with matching keys

Below is the given array : [ { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": "Pen", "Quantity": "1120" }, { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": " ...

The entrance animation kicks off while the exit animation is still in progress

I am looking to implement a slide and fade transition in my Vue routing. The effect I am trying to achieve can be seen here: https://discord.js.org/#/docs/main/stable/general/welcome In this desired effect, the "old" page slides to the right and fades out ...

Assistance with jQuery in Javascript is needed

Currently, I am in search of an effective vertical text scroller. My desired scroller would move vertically in a continuous manner, ensuring there is never any empty space while waiting for the next text to appear. I am open to using either JavaScript or ...

Can I utilize p5.Vector.fromAngle() in Vue JS?

Incorporating P5 into a Vue application can be achieved using the following code snippet: let script = p5 => { p5.setup = _ => { this.setup(p5) } p5.draw = _ => { this.draw(p5) } } this.ps = new P5(script) While functions like ba ...

Getting the input from an HTML editor and inserting it into a textarea using JavaScript

Currently, I am in the process of developing an HTML editor for a project. I have downloaded a program online that I am attempting to customize according to my requirements. However, I am encountering difficulties when trying to retrieve the inner HTML of ...

Unable to retrieve the API key in Nuxt framework

I am fairly new to NuxtJS and have been following tutorials on it. I am having trouble displaying the {{planet.title}} on my page. However, when I use {{$data}}, I can see all the planets. I want the title of the planet's name that I have in the slug ...

Tracking a razor ajax form using pace.js has never been easier with these simple steps

I'm currently exploring the use of pace.js with my Razor ajax form. The form generates a Partial View upon submission. Pace.js, as per its documentation, automatically monitors all ajax requests lasting longer than 500ms without any additional configu ...

How can I fix the error "rootRef.current.contains is not a recognized function" when using the Transition Component in react-transition-group with the latest versions

I am in the process of updating a project from Material-UI 4 to MUI v5, and I have also upgraded react to v18. We utilize the Transition component from react-transition-group within a Modal in one of our components. However, I encountered an error stating ...

Issues encountered with Angular POST requests

I have established a registration and login system using passport.js. Additionally, I am incorporating Angular.js in the front-end. However, when Angular is used, the user signup process does not work as expected. Below you can find the code snippets for b ...

Tips for transferring a DotNetObjectReference to a JS DOM event

My goal is to implement JS drag & drop in Blazor, which is working well overall. However, I am facing an issue where I want to set a custom drag image during the ondragstart event. Below is a snippet of my code: <div class="some-draggable-conta ...

What is the process of modifying the 'Access-Control-Allow-Origin' header?

Currently working on a small app that utilizes Firebase, Axios, and VueJS. Interestingly, when testing the app in Firefox, a PUT request functions correctly. However, upon testing it in the latest version of Chrome, an error message pops up: There was a ...

Chaining promises: The benefits of attaching an error handler during Promise creation versus appending it to a variable containing a promise

function generatePromise() { return new Promise((resolve, reject) => { setTimeout(reject, 2000, new Error('fail')); }); } const promise1 = generatePromise(); promise1.catch(() => { // Do nothing }); promise1 .then( ...

Showcasing international data using a table in Vue.js

As I work on creating a page that includes a section dedicated to products, I have encountered a challenge. Within the product data, there is an attribute called id_categoria which corresponds to a category. Instead of displaying the category ID, I want to ...

Is it possible to utilize WebAssembly in JavaScript to access the memory of a C struct directly?

Looking at the C code snippet below, there is a struct defined as follows typedef struct { ValueType type; union { bool boolean; double number; Obj* obj; } as; } Value; The ValueType enum used in the struct is defined a ...