Difficulty capturing emitted events from child components in Vue.js2

Currently, I'm working on developing a Bootstrap tabs component using Vuejs. The tabs component is divided into two parts - the parent tabs-list component that contains multiple tab-list-item components. Take a look at the code for both these components:

//Vue component template for tabs list.
Vue.component('tabs-list', {
    template: `<ul class="nav nav-tabs nav-justified" role="tablist">
                <tab-list-item v-for="concept in concepts" :key="concept.id" :concept="concept" :selected="concept.active">{{ concept.title }}</tab-list-item>
            </ul>`,
    data() {
        return { 
            activeTab: 1,
            concepts: [ { title: 'Tab A', id:1, active: true}, 
                        { title: 'Tab B', id:2, active: false},
                        // Add more tab details as needed
            ]
        }
    },
    methods: {
        tabItemClicked(concept) {
            console.log(concept);
            this.activeTab = concept.id;
            this.concepts.forEach(tab=> {
                tab.active = (tab.id === concept.id);
            });
        }
    }

});

//Vue component template for tab list item.
Vue.component('tab-list-item', {
    props: ['concept', 'selected'],
    template: `<li role="presentation" :class="{active:concept.active}">
                <a :href='computedHref' :aria-controls="ariaControls" role="tab" data-toggle="tab" @click="tabClicked">
                    <img :src="aquaImage" class="image-responsive concept-image img-active">
                    <slot></slot>
                </a>
            </li>`,
    computed: {
        computedHref: function() {
            return "#concept"+this.concept.title 
        },
        ariaControls: function() {
            return "concept"+this.concept.title 
        },
        aquaImage: function() {
            return "/images/"+this.concept.title+"-aqua.png"
        }
    },
    data() {
        return {
            isActive: false
        }
    },
    mounted() {
        this.isActive = this.selected;
    },
    methods: {
        tabClicked: function() {
            this.$emit('tabItemClicked', [this.concept]);
        }
    }
});

My issue lies in the fact that my tab-list-item should emit an event named tabItemClicked when any of the tabs is clicked. Strangely, nothing appears in the console log. While examining the Vue developer console, I did notice the event being emitted. Why isn't it being captured by the parent tabs-list method? Any assistance would be highly appreciated!

Answer №1

In order to properly handle the event, you must explicitly set up an event listener in the parent component template

Vue.component('tabs-list', {
    template: `<ul class="nav nav-tabs nav-justified" role="tablist">
                <tab-list-item v-on:tabItemClicked="tabItemClicked" v-for="concept in concepts" :key="concept.id" :concept="concept" :selected="concept.active">{{ concept.title }}</tab-list-item>
            </ul>`,
    //....,
    methods: {
        tabItemClicked(concept) {
            console.log(concept);
            this.activeTab = concept.id;
            this.concepts.forEach(tab=> {
                tab.active = (tab.id === concept.id);
            });
        }
    }
}

Answer №2

When using camelCased custom events, triggering in the parent does not work as expected. To fix this issue, replace

this.$emit('tabItemClicked', [this.concept]);
with
this.$emit('tab_item_clicked', [this.concept]);
. For more information, refer to https://github.com/vuejs/vue/issues/4044

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

Having trouble removing just one element from an array in Redux. Any suggestions on how to make it work properly?

I'm currently working on creating a dynamic algorithm for removing an item from an array. Reducer: import { LOAD_PAGES, REMOVE_PAGE } from "./dynamicMenuActions"; export const initialState = { pages: [] }; export const dynamicMenuReducer = (state ...

Guide on Crafting an Interactive Breadcrumbs Component

How can I implement product category breadcrumbs on the product page? These breadcrumbs will represent the parent category of the product. I am utilizing Next.js and Strapi for this project. For example, here is a screenshot showing how it should look: ...

Angular (2/4) application utilizing custom-named routing within a single page architecture

I'm currently working on an Angular application that consists of a login component and a home component which serves as the main handler for the entire single page application. Additionally, I have three more components named users, each with function ...

Error in syntax: An unexpected token was encountered during an AJAX request

I am currently working on a project that involves looping through multiple JSON files within a directory called "trips" and extracting data from each file to display on the front end of the website. However, I'm encountering a persistent error message ...

Small jumps occur when implementing the scrollTop jquery animation

I've encountered an issue with the scrollTop jquery animation that I can't seem to resolve. It seems to micro-jump right before the animation, especially when there is heavier content. I'm puzzled as to why this is happening... Here's ...

Can I simultaneously utilize submit and ajax functions?

As I work on CRUD for our website, the approach we are taking involves using submit. However, there are occasions where I need to pass data from a JS file to my controller (I am using Codeigniter). I am now considering whether it is common practice to do ...

There seems to be a problem as exits.success is not a recognized function -

Currently, I am exploring how to utilize Sails.js with the node-machine-syntax specifically in the context of listing flights. The code snippet below outlines my attempt at achieving this: /** * FlightsController * * @description :: Server-side actions fo ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

Using boolean flags in JavaScript and jQuery

I'm having trouble setting a boolean flag in JavaScript/jQuery. I thought that the flags should change globally after clicking btn1, but for some reason they remain unchanged when clicking btn2. What am I missing? JavaScript: $(document).ready(funct ...

Identifying the moment a member receives a role using my Discord bot built with discord.js

I am currently working on detecting when a user is assigned a specific role on a server. Here is the code I have been using: // Require the required discord.js classes const { token } = require('./config.json'); // Create a new client instance ...

Enhancing Vue.js Scripts with Laravel Localization Language-Strings

Within my vue.js script, I have successfully implemented a sweetalert using two Laravel localization language strings. Now, I am attempting to utilize the same language strings as data properties in another vue.js component script. The issue arises when t ...

The application of texture to a sphere in Next.js with Three.js seems to be malfunctioning

Hi there, I'm having some trouble getting a texture to apply correctly to a sphere within a Next.js component. I've attempted it with the code provided below, but all I see is a black ball rendering instead. I suspect it might have something to ...

Can you incorporate personalized icons in ReactJS?

Is there a way to incorporate my personally designed custom icons, available in both SVG and TTF formats, into a React project? I am interested in using these icons in my navigation bar, such as creating a unique home icon for the home button. ...

Synchronize your store by utilizing cookies in the nuxtServerInit function of NuxtJS

I am currently working with NuxtJS's auth module and attempting to retrieve the Bearer token along with a custom cookie that holds a sessionType during nuxtServerInit in order to update the store through a mutation. However, I am facing an issue where ...

Inquiring about building a comprehensive AJAX website: SEO, Google index, design templates

I'm currently developing a fully AJAX-based website. My focus right now is on implementing page navigation and content display without the need for page reloading. Here's my approach: <html> <head> <!--CSS--> .hidde ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

Exploring the world of jQuery and Ajax: Experimenting with implementing a POST method through Ajax and retrieving the response in HTML

Hey guys, I'm currently attempting to set up a basic HTML post method using Ajax. Take a look at the code snippet below: <?PHP function fetchInstagramData($url) { $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => ...

Troubleshooting a Global Search Problem with Regular Expressions in Javascript

I am facing a minor problem. Here is the snippet of code I am working with: var result1=content.match("/<a [^>]*href\s*=\s*[\"']([^>\"']*)[\"'][^>]*>/gi")[1]; This code is not returning any value. Al ...

What is the best way to transfer GitHub OAuth information to a client?

I am in the process of implementing Github authorization and then sending received JSON data to the client. After doing some research, I came across a helpful tutorial at The tutorial suggests following this path: "/" -> "/login" -> "/redirect" -&g ...

Value binding in Angular being passed to ng-click function rather than the actual value

An HTML link is causing me some trouble: <div class="menu-item" ng-repeat="pageName in pages"> <a ng-click="routing.open('{{pageName}}')">{{pageName}}</a> </div> When clicked, this link triggers the 'open' ...