Having trouble with VueJS ref not preventing the default form action on submit?

Within my <script> tag, I currently have the following code:

render(createElement) {
 return createElement("form", 
   {ref: "formEl" ,
     on: {submit: this.handleSubmit}
   }, 
   [ <insert create form inputs here> ]);
}

handleSubmit(e) {
 e.preventDefault();
 //Other stuff that also rely on using e
}

When a submit button is placed inside the form, handleSubmit works perfectly. However, if I were to use this.$refs.formEl.submit(), HandleSubmit does not run.

I tried a solution mentioned in: VueJs 2 - preventDefault() on $refs.form.submit()

By adding an event listener like this:

this.$refs.form.addEventListener("submit", this.handleSubmit);

Unfortunately, this approach did not solve the issue.

Edit (After Comments): To explain further about why it "did not work": when clicking a submit button within the <form> tags, HandleSubmit() actually runs twice (possibly due to adding a listener twice) I added some console.log() statements to handlesubmit and noticed nothing displayed on the console.

The component is written in Typescript using classes, and I am certain it is located in the equivalent of the methods section of the component for typescript: (inside

export default class ClassName extends Vue {}
)

What I observed is that when attaching a button outside the <form> tag that triggers the submit() method on the reference, the default action of updating the URL with the form contents occurs.

Answer №1

Everything seems to be functioning correctly (no need for a ref). I haven't encountered any issues with duplicate submissions.

I created this component using Typescript with classes, and I'm quite confident that it is located in the methods section of the component for Typescript: (within

export default class ClassName extends Vue {}
)

You're absolutely correct.

However, here's a brief demonstration in Javascript. (The Typescript version should be very similar).

new Vue({
  el: '#app',

  components: {
    TheForm: {
      props: {
        prevent: Boolean
      },
      
      render(createElement) {
        return createElement("form", {
          //ref: "formEl",
          on: {
            submit: this.handleSubmit
          }
        }, this.$slots.default);
      },

      methods: {
        handleSubmit(e) {
          if (this.prevent) {
            e.preventDefault();
          }
          //Other actions that also require 'e'
        }
      }
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7006051530425e465e4141">[email protected]</a>"></script>

<div id="app">
  <p>Clicking on this should do nothing, as the default page redirect behavior is prevented.</p>
  <the-form action="/should-be-prevented" prevent>
    <input type="submit" value='Perform "prevented" submission' />
  </the-form>

  <p>This should behave like regular submit buttons. After submission, the entire screen should go blank (indicating redirection elsewhere).</p>
  <the-form action="/should-redirect">
    <input type="submit" value='Do "normal" submission' />
  </the-form>
</div>

Submitting the form with ref:

new Vue({
  el: '#app',
  
  components: {
    TheForm: {
      props: {
        prevent: Boolean
      },
      
      render(createElement) {
        return createElement('form', {
          on: {
            submit: this.handleSubmit
          }
        }, this.$slots.default);
      },

      methods: {
        handleSubmit(e) {
          if (this.prevent) {
            e.preventDefault();
          }
          else {
            this.$el.submit(e);
          }

          //Other actions that also require 'e'
        }
      }
    }
  }
})
form {
  border: 2px dotted lightgray;
  margin: 1rem auto;
  padding: 1rem;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3c5c6d6f3819d859d8282">[email protected]</a>"></script>

<div id="app">
  <the-form ref="form1" action="/should-be-prevented" prevent>
    This form should remain unchanged, since the default page redirect behavior is disabled.
  </the-form>

  <the-form ref="form2" action="/should-redirect">
    This should work similar to standard forms. Upon submission, the entire screen needs to go blank (to indicate redirection).
  </the-form>

  <hr />
  <p>Note that these buttons are <strong>outside</strong> their respective forms to showcase programmatic form submission triggering. </p>
  <input @click="$refs.form1.handleSubmit($event)" value='Perform "prevented" submission' type="button" />
  <input @click="$refs.form2.handleSubmit($event)" value='Perform "normal" submission' type="button" />
</div>

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

Is there a way to create a function that is able to return both a value and a promise

Assume I need to fetch a value only if an object is already present in my model. Otherwise, I should retrieve the output of an endpoint service: model.getDoohkyById = function( id ){ if( this.data ) { if( this.data.length > 0) { ...

Utilizing Javascript Conditional for Substitution

Currently, I have a JavaScript function that replaces all links with registration messages: <script> function replaceLinks() { var links = document.querySelectorAll('.restore a:link'); for (var i = 0; i < links.length; i++) { ...

Guide on utilizing substring string functions in the updated version of Selenium IDE

I am facing a challenge with extracting the word "Automation" from a given string "Welcome to the Automation World" using Selenium IDE Record and Play feature. I have tried using the execute script command, but it doesn't seem to be working as expecte ...

Enhance chat functionality by integrating MySQL database to store and update chat messages

I'm currently working on developing a chat system that allows users to enter the chat and send messages. The messages are being stored in a MySQL database, and here is a snippet of my code... <script> $('input[type=text]').on('ke ...

Incorporate a directive dynamically within a separate directive

Introducing the table-div directive, which is responsible for rendering both the header and body of a table. Each row within tbody has the option to incorporate additional functionality through a custom directive that can display data linked to its parent ...

Is selectpicker acting up?

Currently, I am troubleshooting a filter feature on a website that utilizes jQuery with JSON data. Everything was functioning properly until recently when an error started appearing: The selectpicker function is not recognized I would greatly appreciat ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

Click Function for Modifying the Content of a Popup Window

I'm a beginner in JavaScript and I need help figuring out how to achieve the following task. Essentially, my goal is to have lines of code like this: <a onclick="JavascriptFunction(0000000)"><img src="image1.png"></a> The number w ...

What are the steps to successfully submit my form once all the validation requirements have been met?

I successfully completed the validation process, but I am encountering an issue when trying to submit the form. An error message pops up indicating that there is an error related to a specific field (e.g., special characters being used). However, even when ...

Input information into a JSON container

I've been struggling to find a solution for this issue. Here's the JSON variable I'm working with, which includes the names "rocky" and "jhon": var names = [ "rocky", "jhon" ]; Now, I need to add a new val ...

IE and Firefox display different responses when encountering an empty XML document

When working with jQuery to read an XML file, I occasionally encounter the situation where the XML is empty. In this case, I anticipate that the error function (no_info) will be triggered because the file is not formatted as expected for the dataType. Int ...

I can't understand why my server is displaying an error on the browser stating "This site can't be reached ERR_UNSAFE_PORT" while it is functioning flawlessly on the terminal

I have created an index.html file, along with index.js and server.js. In the server.js file, I have included the following code: const express = require("express"); const path = require("path" ); const app = express(); app.use(" ...

Is it possible to manage how many times a functional react component re-renders based on changes in its state?

For my practice e-commerce app, I have a functional component called "Shop" with two states: [products, setProducts] = useState([10ProductObjects]) and [cart, setCart] = useState([]) Upon the initial render, 10 products are loaded and each Product compone ...

Using React Bootstrap to conditionally render columns within an array map

Within my React application, I am currently utilizing the map function to generate Bootstrap columns in the JSX code of the render method. One specific attribute within the array object I'm mapping is named "taken." Depending on whether this attribute ...

Having issues with function arguments and parameters not functioning correctly in a Vuetify project when utilizing the "this" keyword?

In my current Vuetify project, I am trying to achieve a similar functionality as shown in the following plain HTML/JavaScript example: <body> <button id="anid" onclick="idcheck(this.id)"> </button </body> <script> function ...

What is the best way to reference the className within nested SCSS when working with Next.js and React.js?

I am working on customizing a navbar that includes a hamburger button. My goal is to change the style, specifically the bar color and the appearance of the hamburger button, upon tapping. I have already attempted using &:active and .activeBar in the SCSS f ...

Managing Pop-Ups when browsing on Internet Explorer

I've been working on an Excel VBA macro that automates several tasks on the Medicare website. The macro opens IE, logs in, compares claims, and alerts me to any differences found. However, I've encountered a problem during the log-in step, specif ...

Error: Unable to locate module: Unable to resolve './Page.module.css' in Next.js version 13

When I run npm run build on Vercel and Heroku, I encounter an error that does not occur on my local computer: The error message is Module not found: Can't resolve './Page.module.css' I am trying to import this file from app/page.tsx, and b ...

Tips for effectively implementing Google Publisher Tags Ads in Nuxt Composition Api projects

Utilizing the Composition API, I successfully integrated a GPT ad service. Everything was working fine upon the initial page load, but I began encountering issues when navigating between pages - my ad area would disappear and error messages would pop up. ...

Route protection is ineffective when dealing with two observables simultaneously

After writing the route guard as shown below, I encountered an issue with the else statement that was not returning a result, even though it should have. Surprisingly, there were no errors either. this.hotelSettingsService.get().pipe(map(res => { ...