Vue: event triggers malfunctioning and components unresponsive

I am new to Vue.js and I'm attempting to trigger an event from my grand-child component (card) to the child component (hand) and then to the parent component (main):

card (emit play event) => hand (listen for play event and emit card-play event) => main (listen for card-play event)

The play event should trigger the card-play event.

In the card component, I emit a "play" event when the card is clicked. In my hand component, I listen for the "play" event in order to emit the "card-play" event to the parent (main). However, neither events are being emitted nor are the elements (button element) working.

If I directly include the card component in the main component, everything works fine. But when I add another component (hand) between them, nothing works as expected.

Here is my code:

new Vue({
    name: 'game',
    el: '#app',

    data: state,

    template: `
        <div id="#app">

            <card :def="testCard" @click.native="handlePlay2" />

            <transition name='hand'>
                <hand :cards="testHand" v-if="!activeOverlay" @card-play="testPlayCard" />
            </transition>

        </div>
    `,

    methods: {

        testPlayCard(card) {
            console.log('You played a card!');
        },
        handlePlay2() {
            console.log('You played a card!');
        }
    },

    created() {
        this.testHand = this.createTestHand();  
    },

    computed: {
      testCard () {
       return cards.archers
      },
    } 

});

Here are the components:

/* ----- CARD COMPONENT ----- */
Vue.component('card', {
    props: ['def'],
    template: `
        <div class="card" :class="'type-' + def.type" v-on:click.native="firePlayEvent">

            <div class="title">{{ def.title }}</div>
            <img class="separator" src="svg/card-separator.svg" />
            <div class="description">
                <div v-html="def.description"></div>
            </div>
            <div class="note" v-if="def.note">
                <div v-html="def.note"></div>
            </div>
            <button>bos</button>
        </div>
    `,
    methods: {
        firePlayEvent: function() {
            this.$emit('play');
            console.log("play event is emitted???")
        }
    },
});


/* ----- HAND COMPONENT ----- */
Vue.component('hand', {
    props: ['cards'],
    template: `
        <div class="hand">
            <div class="wrapper">
                <!-- Cards -->
                <card v-for="card in cards" :key="card.uid" :def="card.def" @play=handlePlay(card) />

            </div>
        </div>
    `,
    methods: {
        handlePlay(card) {
            this.$emit('card-play', card);
            console.log("custom event card-play>>");
        }
    },
});

I am storing all data in state.js:

// Some useful variables
var maxHealth = 10
var maxFood = 10
var handSize = 5
var cardUid = 0
var currentPlayingCard = null

// The consolidated state of our app
var state = {
  // World
  worldRatio: getWorldRatio(),

  // TODO Other things
  turn: 1,

  //
  players: [
    { name : 'Humoyun' },
    { name : 'Jamshid' },
  ],

  //
  currentPlayerIndex: Math.round(Math.random()),

  //
  testHand: [],

  //
  activeOverlay: null,

  //

}

Answer №1

Upon reviewing your github link, I made some adjustments to ensure it functions correctly:

Initially, I noticed there was a CSS element preventing click events on a card. To enable the event trigger, you should delete the pointer-events: none line located at 239 in your css file.

Additionally, you can omit the use of .native event modifier when clicking on your card:

<div class="card" :class="'type-' + def.type" @click="firePlayEvent">

After implementing these changes, clicking on a card will display the following message in the console:

custom event card-play>>
ui.js:43 play event is emitted???

Subsequently, the card will be successfully removed as intended.

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

When making an Ajax post request, the loading indicator may not appear

I've implemented the jQuery code below for an autocomplete input field, but I'd like to have a spinner display while waiting for the response from the server. In my code, I'm using search: to show the loading div and open: to hide it. The s ...

What is the best way to save the properties of elements in an array of objects within another array?

I have obtained attributes from objects within an array that I need to store in another array. Here is the data I am working with: My goal is to extract the `displays` name attribute and save it in the `opt[]` array, which would result in something like t ...

Creating a Vue application utilizing a function with an unspecified purpose

Looking to create an app with a function that is currently undefined. On the production server, there is a function called __doPostBack which I am calling from my Vue app like this: getLabel(templateName) { __doPostBack(templateName, ""); } Afte ...

CSS style takes precedence over inline JavaScript transitions occurring from a negative position

I am puzzled by a JavaScript fiddle I created which contains two small boxes inside a larger box. Upon clicking either of the buttons labeled "Run B" or "Run C", the corresponding box undergoes a CSS transition that is controlled by JavaScript. Below is t ...

Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values. Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the ...

I need help figuring out how to retrieve the full path of an uploaded file in JavaScript. Currently, it only returns "c:fakepath" but I need

Is there a way to obtain the complete file path of an uploaded file in javascript? Currently, it only shows c:\fakepath. The file path is being directly sent to the controller through jquery, and I need the full path for my servlet. Are there any alte ...

Ways to showcase every resource from an API in React JS

I need help with adding code to display products along with their images from an API in my existing code. Can someone assist me with this? import React, {useState, useEffect} from 'react' import "bootstrap/dist/css/bootstrap.min.css" im ...

Fastify route handler failing to start after onRequest hook is executed

I am currently working on a fastify application that needs to capture the raw body of post requests for authentication purposes. After extensive research, I discovered that fastify does not have native support for this feature. The solutions I found online ...

How can we prevent users from changing URLs or accessing pages directly in Angular 7 without using authguard?

Hey there! I am trying to find a way to prevent users from accessing different pages by changing the URL, like in this scenario. Is there a method that can redirect the user back to the same page without using Authguard or any Modules? I have a StackBlit ...

I'm working on separating the functionality to edit and delete entries on my CRM model, but I'm having trouble finding a way to connect these buttons with my data fields

I am encountering some difficulties while trying to implement separate functionality for editing and deleting items on my CRM model. I have already created the necessary API in Angular, but I am struggling to bind these buttons with my field. Any assistanc ...

Tips for adding new items to a Masonry Image List using React MUI

As I experiment with utilizing the React MUI Masonry Image List alongside the infinite scroll, I've found that they complement each other quite well. However, a challenge arises when appending new images to the Masonry image list. While I can success ...

The process of utilizing RxJS for server polling is a

My goal is to constantly update client-side data by polling the server. To achieve this, I have set up a dispatcher that triggers an action labeled FRONT_PAGE. This action is initiated when the app launches and the client is supposed to send requests every ...

Utilizing VueJS to display content conditionally with v-show and JSON Data

I'm in the process of creating a VueJs portfolio where I want to showcase projects based on selected tags. Below is my code: <script lang="ts"> import projectsData from "../projects.json" export default { data() ...

What factors determine how a React component should be re-rendered based on a specific file?

I am facing a challenge with a file that stores an array of objects. There is a component responsible for fetching data from this file and rendering the list. The issue arises when the file gets updated externally, as I need the component to reflect these ...

When clicked, elevate the element to the top of the window with an offset

Is there a way to click on this button, which is located within an accordion section header, and have it automatically move to the top of the page based on the window size? It seems like it should be a simple task, but sometimes after a long day things ca ...

Creating personalized hooks that rely on React query requests

Utilizing a series of custom hooks, I am able to fetch data and perform various calculations based on that data. One particular hook calculates the total amount that should be set aside monthly for future expenses, using the output from previous data-fetch ...

What are the steps to ensure that data retrieved from an API is accurately displayed in a table?

My current goal is to collect data from the crypto compare API and display it in a table format. Although I am able to generate the necessary elements and append them to the table body, I am facing an unusual issue. Each time I use a for loop to iterate th ...

AngularJS - smooth scrolling with $anchorScroll duration

While going through the AngularJS documentation, I have not been able to determine whether $anchorScroll has a duration or easing option for smoother scrolling to elements. The documentation only shows: $location.hash('bottom'); // call $ancho ...

Steps to finish (refresh) a mongoDB record

Currently, I am dealing with the following scenario: An API request from one service is creating multiple MongoDB documents in a single collection. For example: [ {_id: 1, test1: 2, test: 3}, {_id: 2, test1: 3, test: 4} ] Subsequently, a second service ...

Remove the active class after it has been clicked for the second time

Currently, I am working on a menu/submenu system where I want to toggle active classes when clicked. However, I encountered an issue - if the same menu item is clicked twice, I need to remove the active class. Initially, I tried using jQuery's toggleC ...