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

The function onReady() fails to trigger the execution of $.getJSON() upon page restoration in the browser

Initially, I want to mention that the code below functions perfectly when I launch a new browser tab and enter my web server's URL. It also works fine when I reload the page (using F5 or Ctrl-R). However, it only partially works if I reopen a closed b ...

The functionality of Jquery radio:checked is not behaving as desired

Currently, I am in the process of learning jquery. I have created a basic html file with some jquery validations, however, they are not functioning as expected. The main problem is: If I input my name first and then check the checkbox, everything works co ...

Vue.js development processes are running smoothly, but experiencing issues with building and previewing the

I am working on a Vite + Vue.js 3 project in TypeScript. When I run npm run dev and go to http://localhost:5173/, everything works fine. But when I run npm run build && npm run preview and visit http://localhost:4173/, the website gives me a JavaScript err ...

Enhancing Browser Experience: The correct method for dynamically adding an AngularJS controller through a Chrome Extension's Content

Currently, I am in the process of developing a Chrome extension using AngularJS. To attach a controller to the required DOM elements on a webpage, I have been utilizing the following content script code: setController() { if(this.setContollerConditio ...

What is the method for adding an HTML tag that includes an md-checkbox and md-icon?

I am currently utilizing angular material and angular js to dynamically add a new HTML div when a certain function is triggered from the view. Here is my view setup: <div id = "main_row" ng-click="defCtrl.submit()"> </div> This is wh ...

If I click on a different VueJS menu, make sure to close the current menu

When using a component menu, each item is displayed independently. However, I would like the open items to close automatically when I click on another item with the menu. I employ a toggle functionality on click to control the opening and closing of the c ...

What is causing the 'info' object to be undefined?

transporter.sendMail(mailOptions,(error,info)=>{ if(error) console.log(error) console.log('Message Sent: '+info.messageId) console.log('Preview URL: '+nodemailer.getTestMessageUrl(info)) res.redirect('contacts', ...

Determine the cost for every individual line

I need help figuring out how to calculate the price for each row. Whenever I choose a quantity, it's showing the same price for both rows. Check out my demo here: https://jsfiddle.net/keyro/fw8t3ehs/2/ Thank you in advance! HTML: <table class=" ...

Customizing the appearance of selection dropdown options in React

Is it possible to customize the styling of the choices in a React input dropdown? For instance, I am interested in creating an autocomplete dropdown that presents the options neatly arranged in columns. Essentially, I want to design a dropdown data grid t ...

Retrieving values from objects using Typescript

I am facing an issue while trying to retrieve a value from an object. The key I need to use belongs to another object. Screenshot 1 Screenshot 2 However, when working with Typescript, I encounter the following error message. Error in Visual Studio Is ...

Is it necessary to store tokens in cookies, local storage, or sessions?

I am currently utilizing React SPA, Express, Express-session, Passport, and JWT. I find myself puzzled by the various client-side storage options available for storing tokens: Cookies, Session, and JWT/Passport. Is it necessary to store tokens in cookies, ...

What is the process for implementing optional chaining on a JSON object?

I'm currently facing an issue where I need to compare a value within a JSON object with a variable. if (resp.userdetails.name == username) { // do something } The challenge arises when not all resp objects contain the userdetails property, resulting ...

What is causing this form to submit?

I need help with sending emails via AJAX. My problem is that the form keeps submitting and refreshing, even though I haven't used GET to send anything in the URL. HTML: <form onsubmit="ajaxEmail(); return false;" > <input type=" ...

With jQuery's .text() method, it is possible to modify the first span's Bootstrap class, but not the

As someone who is new to javascript, html, and jquery, I have been trying to change the text of 2 span elements in the same div using jquery's .text() command. Despite going through various solutions provided by different questions, none seem to work ...

Verification of user input field

For this mini deposit app, I needed to implement validation for the input field to check for three different conditions: no blank entries, only numerical values, and no negative numbers. Despite having the functionality, my attempts at implementing validat ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

Communicate through PHP and JavaScript chat to display HTML content in the chat window

I have been attempting to display HTML output in the chat window but instead, it is showing the HTML code. Here are the two files involved in the chat system: chat.js `function chatHeartbeat(){ var itemsfound = 0; if (windowFocus == false) { var ...

AngularJS does not hide the Onsen UI modal

I am new to working with angularjs and onsen ui. I have implemented a modal in an ajax request, which is supposed to hide upon successful response. Everything seems to be working fine, except for the fact that when I navigate back to the page, the modal re ...

Python raises a KeyError if JQuery is included

I have encountered an issue with the code snippet below, where I am attempting to define a variable within the HTML. Oddly enough, when I exclude the JQuery script, everything functions as expected. However, upon reintroducing the JQuery script, the functi ...

Interacting with ref objects and functions in Vue with Leaflet

I have implemented a leaflet map in my vue project. Here is the relevant Vue code: <div style="height:70vh; width:100%; position: relative;"> <l-map ref="map" :zoom="maps_obj.zoom" :center="[maps_obj.latitu ...