The $emit method in Vue seems to be ineffective when used on the parent component, yet it functions properly when used on the

I have a component called "register" which contains an event listener @submit.prevent inside the template, and I am using $emit to send the data. When I console.log within the method of the component itself, it works fine. However, when I try to access the data in my main JavaScript file, nothing happens; there are no errors either.

Here is an example of my component:

Vue.component("register", {
  props: {
    form: Object
  },
  template: `
  <div class="container">
    <div class="row">
      <div class="col-sm-4 offset-4">
        <form @submit.prevent="goRegister">
          <div class="form-group">
            <label for="username">Username</label>
            <input type="text" class="form-control" id="usernameRegister" aria-describedby="emailHelp" placeholder="Enter username" v-model.trim="form.username" required>
        </form>
      </div>
    </div>
  </div>
  `,
  methods: {
    goRegister() {
      this.$emit("doRegister", this.form);
    }
  }
});

This is how I use the component in my HTML parent element:

<register v-on:do-register="handleRegister" :form="forms"> </register>

And here is the code snippet from my Vue main.js:

new Vue({
   data:{
   forms: {
      username: null,
      email: null,
      password: null,
      name: null,
      age: null
}
}, 
methods : {
    handleRegister() {
      console.log(this.forms.username);
    }
}
})

I tried to log the method handleRegister, but nothing happened. Could there be something missing in my parent component?

Answer №1

To change the name of the event you are emitting in VueJS, remember that camelCase and kebab-case are not automatically converted for emitted event names. If you want to listen for the do-register event, you must emit it as do-register and not doRegister:

this.$emit('do-register', this.form);

But what if you still wish to emit a doRegister event? In this scenario, you will have to emit it as an all lowercase string.

Keep in mind that bound event names in inline attributes are case-insensitive due to HTML limitations where attribute names are transformed to lowercase by the browser. So, if you prefer to emit an event without using kebab-case, then you should do:

this.$emit('doregister', this.form);

In the parent component's template where you consume the event, make sure to listen for the doregister event:

<register v-on:doregister="handleRegister" :form="forms"> </register>

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

What is the best way to streamline a state-dependent getter, with a focus on adhering to SOLID principles?

Is there a more user-friendly way to retrieve different data based on the type in my Angular component? I'm considering separating the component into two: one for phone and one for email. However, I'm concerned about duplicating most of the logi ...

Submitting an ajax form with the use of the symbol '&'

I am currently working on a form submission using the .ajax() method. Within my script, I have the following code: data: dataString, The variable dataString is composed of: var list = $('.listsummary').val() The listsummary class is assoc ...

Tips for importing a .ts file into another .ts file within an Angular 5 application

I have a bunch of utility methods stored in a file called utils.ts that I want to reuse across multiple components. I'm not sure if it's even possible, and if it is, where should I place the import statement and what would be the correct syntax. ...

How can we leverage JavaScript to create logistic regression models for datasets and derive the beta-coefficients?

Exploring Logistic Regression in JavaScript In my current project, I am looking to fit a multi-variate logistic regression model to a dataset using JavaScript. My main goal is to extract the beta-coefficients for this model. Can anyone provide guidance on ...

Passing data from a Vue.js component to a router in index.js

I am attempting to transmit a JWT token value from the component Login.vue and verify it in the router/index.js before directing the user to the next page. Login.vue: <script> import axios from "axios"; export default { name: "Login", m ...

Hiding a Blogger section when its widget is not visible

Take a look at this code: <b:section id='page-list'> <b:widget id='PageList1' locked='false' type='PageList' version='2' visible='true'> </b:widget> </b:section> I wa ...

What is the best way to link a multi-select element with an array of objects?

How can I bind a select element with a model to get/set the value and populate it from a list using angular 1? Currently, I'm able to bind it from UI to model, but not vice versa. What am I doing wrong? HTML: <div ng-controller="MyCtrl"> ...

Determine the shared elements within a single array by utilizing Javascript

I have the following array of mergeUniqueItems: var mergeUniqueItems = ["-JsDEcxz_ZSGFLKwd1QM", "-JsJ2NXGDYKI6QRsuXVK", "-JsJ2RK-kOG2eGcG04xF", "-JsJ2RK-kOG2eGcG04xF", "-JsJ2YLPiP6751zh8geS"] After using this code snippet, I encountered an issue: ...

Using database entries to generate dynamic routes in express.js without the need for a server restart

I have created a custom Express instance for my KeystoneJS v5 app that serves data stored in a Postgres database with the following model: CREATE TABLE "Link" ( id integer DEFAULT PRIMARY KEY, customer text, slug text ); I've set up dyna ...

How can I trigger a method after the user has finished selecting items in a v-autocomplete with multiple selection using Vuetify?

After multiple selections are made in a v-autocomplete, I need to trigger a method. However, the @input and @change events fire after each selection, not after the full batch of selections. Is there an event that triggers when the dropdown menu closes? Al ...

Utilize socket communication with node.js to monitor and identify user

I'm attempting to find a method to unsubscribe from a Redis channel when the user navigates to another page within our website. I have attempted to detect a disconnect socket event when the user clicks on a link, but unfortunately, the event is never ...

Having trouble with Jquery's Scroll to Div feature?

When I click on the image (class = 'scrollTo'), I want the page to scroll down to the next div (second-container). I've tried searching for a solution but nothing seems to work. Whenever I click, the page just refreshes. Any help would be gr ...

Employing regular expressions within Notepad++ to insert whole numbers into img src within table elements

I have a large table filled with numerous items that require individual images to be added. Let's take a look at the code snippet below. <tr><td><img src=".jpg" width=100 height=100/></td></tr> Although I could manually ...

comparing multiple values separated by commas with JavaScript

I need validation using a comma-separated value format. Within the illustration, there are two fields: "Saloon Price" (value: 10,10,10,10) and "Saloon Offer Price" (value: 11,11,11,11). The first value must be less than the second. Saloon price Value & ...

Seeking the perfect message to display upon clicking an object with Protractor

Currently, I am using Protractor 5.1.1 along with Chromedriver 2.27. My goal is to make the script wait until the message "Scheduling complete" appears after clicking on the schedule button. Despite trying various codes (including the commented out code), ...

What is the method to turn off readonly property for input fields in Laravel?

I'm encountering an issue with my Laravel project. I have a form with an input field that has the readonly attribute set. <input type="text" name="anamFam" id="anamFam" value="{{$aFam->anam_cont}}" readonly> When I click the edit button, I ...

Is there a way to automatically convert a webpage to a PDF when it is requested?

I'm looking to convert the webpage into a PDF file upon request. Below are the scripts I am using: <script> pdfdoc.fromHTML($('#container').html(), 10, 10, { 'width': 110, ...

Switch body class when the navbar's collapse show class is toggled

There are numerous methods to accomplish this task, but I am seeking the most optimal and efficient approach. My goal is to toggle a custom body class when the .navbar-toggle triggers the .show class on the .navbar-collapse element. I'm hesitant abo ...

Issue with accessing container client in Azure Storage JavaScript library

When working on my Angular project, I incorporated the @azure/storage-blob library. I successfully got the BlobServiceClient and proceeded to call the getContainerClient method, only to encounter this error: "Uncaught (in promise): TypeError: Failed ...

Automatic closure of Info Window on Google Maps is not functioning as expected

I have recently developed a map which you can view here. The issue I am facing is that when I click on the layers to see the InfoWindow, they do not automatically close when I click on another layer. The JavaScript code I am using is causing this problem. ...