Vue parent component not receiving events properly

Referring to these sources:

Forum Post Stack Overflow Question

In my project, I am utilizing:

CodeSandbox Example

The setup involves the parent component listening for events emitted by a child component:

  mounted() {
    this.$on("edit-category", (taskItemParam) => {
      console.log("Received edit-category event with payload:", taskItemParam);
    });
    this.$on("delete-category", (taskItemParam) => {
      console.log(
        "Received delete-category event with payload:",
        taskItemParam
      );
    });
  },

The child component, on the other hand,

Edit Category Component

is responsible for emitting two distinct events:

  <div class="modal-body" @click="emitEditCategory()">
    <slot name="name"> Edit Name </slot>
  </div>

  <div class="modal-body" @click="emitDeleteCategory()">
    <slot name="delete"> Delete Category </slot>
  </div>

  methods: {
    ...
    emitEditCategory() {
      this.$emit("edit-category", this.taskItemLocal);
      console.log("Emitting edit-category");
    },
    emitDeleteCategory() {
      this.$emit("delete-category", this.taskItemLocal);
      console.log("Emitting delete-category");
    },
  },

The main query arises as to why the emitted events fail to propagate to the parent component. Understanding the event scope in vue from a child-to-parent hierarchy is essential in addressing this issue.

Answer №1

this.$on is set up to listen for events emitted by the this component, essentially listening to itself.

It’s important to note that the $on api should be avoided as it has been deprecated in Vue3 and can result in poorly designed Vue applications.

If you need to listen for events from a child component, it’s recommended to use v-on, or the shorthand syntax @my-event:

<template>
   <edit-category :taskItem="taskItemLocal" @edit-category="updateCategory" @delete-category="deleteCategory"/>
</template>

<script>
[...]
   methods: {
      updateCategory(task) {
         // Perform desired action
      }
      deleteCategory(task) {
         // Perform desired action
      }
   }
</script>

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

Steps for implementing Onclick event within the <Script> tag to display a div:

I am currently working on a code that allows me to show and hide a <div> element after clicking on an advertisement from any website. This advertisement is generated by a script. How can I implement the onclick event within the <script> tag? T ...

exploring the digital archives for a specific song file on the computer

Currently in the process of building a website, and I am looking to incorporate a search and filter feature for all music content so that users can play it on my player. Wondering if this is possible? Seeking some assistance and creative ideas to make thi ...

Locate all posts associated with the specified User ID

Using mongoose, I am able to populate the "Post Schema" with relevant information about users who create the posts. postModule.js const mongoose = require('mongoose'); const postSchema = mongoose.Schema({ title:String, description:String, date ...

Learn the steps to assign a Base64 URL to an image source

I am currently facing an issue with an image that is being used with angular-cli: <img src="" style="width: 120px; padding-top: 10px" alt="" id="dishPhoto"> The image has a Base64 url named imgUrl. My intention is to set the image source using the ...

Is it possible to utilize the same Context in multiple forms within React?

Is it possible to utilize React Context to store the state of multiple forms, or should each form have its own unique Context? Below is a snippet of code that showcases the use of React Hooks API: In FormContext.js ... import {FormReducer} from './ ...

What's the best way to determine which of the two forms has been submitted in Django?

On my homepage, I have both a log_in and sign_up form. Initially, the log_in form is displayed by default, but when a user clicks on the Sign Up button, the sign_up form appears. These toggles switch depending on which button the user clicks. from django ...

Tips on implementing VueStripe in a vue2 Project

I recently integrated Vue Stripe into my vue2 Project and encountered 2 similar errors in my code : Property 'redirectToCheckout' does not exist on type 'Vue | Element | (Vue | Element)[]'. Property 'publishableKey' does ...

Jest testing in a Vue child component is failing due to the presence of lodash

In this specific instance of my Vue app, I have globally loaded lodash as a Vue plugin in the main.js file: import _ from "lodash" export default function install(Vue) { Vue.prototype._ = _ Vue.mixin({ computed: { _: () => ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...

Significant delay in processing second jQuery Ajax call

Attempting a simple Ajax call with page content refresh using the following code snippet: $("a.ajaxify-watched").bind("click", function(event) { $item = $(this); $.ajax({ url: $(this).attr("href"), global: false, type: "G ...

Turning off and on CSS transitions to set the initial position

Is there a way in javascript to position divs with rotations without using transitions initially for an animation that will be triggered later by css transition? I have tried a codepen example which unfortunately does not work on the platform but works fin ...

Can you explain the concept of a framework operating "on top of" node.js in a way that would be easy for a beginner to understand?

If someone is new to JavaScript, how would you explain the concept of "on top of node.js" in simple programming language? I am looking for a general explanation as well as specific reference to Express on top of node.js in the MEAN stack. Appreciate your ...

Generate a unique token through a personalized form

**HTML** <div ref="addCardForm" id="card-element"> <div class="card_digit_text">Credit Card Number <input type="text" id="cardDigit" name="email" placeholder="0000 0000 0000 0000"> </div> ...

The functionality of Jquery UI is not compatible with version 1.12

Incorporating jQuery UI into my current project has presented some challenges. Both the jquery-ui.min.css and jquery-ui.min.js files are version 1.12, so I opted for the latest jQuery version, jquery-3.2.1.min.js. Specifically, I decided to test the datep ...

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

AJV is failing to validate my body using the function generated by the compile method

Currently, in my API development process with express, I have implemented AJV as a middleware to validate the incoming body data. The version of AJV being used is 6.12.6 Below is the JSON schema named body-foobar.json: { "type": "object& ...

What is the process for invoking a JavaScript function from the code-behind of an Asp.Net application?

Here is a sample of my JavaScript function : function NeedToExport() { alert('Time to export your data!'); } Additionally, in my ASP.NET code behind : Page.ClientScript.RegisterStartupScript(this.GetType(), "ExportKey", "NeedToExport();"); ...

Retrieve information from a JSON API on one server and showcase it on an HTML page hosted on a different server

I have a situation where I need to transfer data from one project (Project1) to another project (Project2). To achieve this, I decided to convert the Project1 data stored in a database into a JSON API and then call it using an HTML page from Project2. Howe ...

Instant Pay Now Option for Your WordPress Website with PayFast Integration

I have encountered an interesting challenge that I would like some guidance on. My goal is to integrate a PayFast "Pay Now" button into a Wordpress.com blog, specifically within a sidebar text widget. The tricky part is that I need the customer to input th ...

Eliminate server-side functionality from the React project's boilerplate template

After cloning and installing the project from https://github.com/react-boilerplate/react-boilerplate, I realized that I only need the client-side portion as I intend to use a pre-existing server (express) for my application setup. Below is an excerpt f ...