Issue with Vue parent component's inability to listen to event emitted by child component

Child component is triggering a custom event:

<template>
  <div id="controls-container" class="controls-container">
    <div class="control-button icon-zoom-in" @click="zoomHandler('+')"></div>
    <div class="control-button icon-zoom-out" @click="zoomHandler('-')"></div>
    </div>
  </div>
</template>

<script>

export default {
    name: "ControlsContainer",
    methods: {
        zoomHandler(direction) {
            console.log("this message will be displayed");
            this.$emit('zoomHandler', direction);
        }
    }
};

</script>

Parent component is not receiving the emitted event:

<template>
  <div id="map" ref="map" class="navigation-map">
    <controls-container @zoomHandler="zoom"></controls-container>
  </div>
</template>

<script>

import ControlsContainer from "./ControlsContainer.vue";

export default {
    name: "NavigationMap",
    components: { ControlsContainer },
    methods: {
        zoom(direction) {
            console.log("message will not display");
            if (direction === "+") {
                this.map.zoomIn();
            } else if (direction === "-") {
                this.map.zoomOut();
            } else {
                // Do nothing
            }
        },
    },

</script>

I have gone through multiple tutorials on this and they all demonstrate the same approach I am following. After spending hours on this, I really hope it's not something trivial...

Answer №1

This can serve as an alternative solution.

<template>
  <div id="controls-container" class="controls-container">
    <div class="control-button icon-zoom-in" @click="zoomHandler('+')"></div>
    <div class="control-button icon-zoom-out" @click="zoomHandler('-')"></div>
    </div>
  </div>
</template>

export default {
    name: "ControlsContainer",
    methods: {
        zoomHandler(direction) {
            console.log("this message will be displayed");
            this.$root.$emit('zoomHandler', direction);
        }
    }
};



<template>
  <div id="map" ref="map" class="navigation-map">
    <controls-container></controls-container>
  </div>
</template>

<script>

import ControlsContainer from "./ControlsContainer.vue";

export default {
    name: "NavigationMap",
    components: { ControlsContainer },
    methods: {
    },
    beforeDestroy(){
      this.$root.$off("zoomHandler")
    },
    mounted(){
      this.$root.$on("zoomHandler", (direction)=>{
        if (direction === "+") {
                this.map.zoomIn();
            } else if (direction === "-") {
                this.map.zoomOut();
            } else {
                // Do nothing
            }
      })
    }
</script>

Answer №2

I've noticed a small issue in your child component - it seems that the <script> tags are missing. Could this be a typo in your question? If they're not included, it could be causing the problem you're experiencing.

Remember not to use Camel Case for DOM attributes, including emitters and custom events.

Consider refactoring your child component to:

this.$emit('zoom-handler', direction);

And for your parent component:

<controls-container @zoom-handler="handleZoom"></controls-container>

You can view a working example on codesandbox.io. To see it correctly displayed, make sure to open the preview in a new window or tab.

Answer №3

Since these elements are not nested, Map cannot be considered the main parent. Trying to force it as the parent creates additional complications. It's simply not worth the trouble.

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

Find the identifier that does not currently exist in the collection of objects

There is a situation where I have an array and an object that consists of arrays of ids, which are essentially permission objects. My goal now is to extract the ids that do not exist in the given object. Can someone assist me with devising the necessary l ...

Access Mixins Throughout Your Entire Vue 3 Application

I'm a beginner with vue and I'm currently exploring the use of Websockets for my project. I want to make my websocket-plugin accessible from every component in my app, so I thought about using 'provide' and 'inject'? In my ma ...

The Jquery confirmation dialogue does not seem to be functioning properly within the Content Place Holder

I've encountered an issue with a JQUERY Confirm dialogue where it works perfectly fine until I place it on a page that is within a masterpage. The confirm alert pops up for a split second and disappears. window.onload = function() { $("#ehi").cli ...

Dead end: bootstrap-vue 2 b-table slots have ceased to function

I've encountered an issue with the b-table component while trying to customize 3 columns using slots. Previously, the code below worked perfectly fine. However, recently it has stopped working without any changes to the code, component, or package ve ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

What is the best way to calculate the number of items in your mongoose reference with a specific field?

I am trying to calculate the number of active Workers that belong to a specific company. Here is an example scenario: const workerSchema = new Schema( { userId: { type: Types.ObjectId, ref: 'User', ...

Why won't the div move when I click it?

Could you please explain why my JavaScript code isn't functioning as expected? The intended behavior is for the 'mark' div to move to the current mouse coordinates upon clicking within the map. ...

Consistent Errors with AJAX POST Requests Despite CORS Enablement

Here is a function I have created for making an ajax post request: function POST(url, data) { $.ajax({ 'type' : "POST", 'url' : url, 'data' : data, headers : { 'Access-Cont ...

In JavaScript, a variable's value can be assigned to another variable using the variable

I have a collection of predetermined variables. I dynamically assign a value to another variable, which ends up representing the name of one of the predefined variables. This allows me to easily determine which set variable to use on a particular section o ...

Incorporate visual elements such as images that resemble checkboxes

I'm searching for an innovative approach to replace the traditional checkbox, incorporating images instead. My idea is to have users click on an image, which will then fade out and reveal a tick box overlay. My inspiration comes from Recaptcha 2, whe ...

Exploring AngularJS ng-repeat features for custom attribute settings

I'm currently facing a challenge in removing multiple repetitive divs by utilizing ng-repeat. <!-- I have 21 of these --> <div class="table-row"> <span class="glyphicon glyphicon-wrench"></span> <label>Chlo ...

Executing XSS Reflected Attack by Loading an External JS Script via POST Parameter

Experimenting with XSS attacks on my vbox machines, just for kicks! I have two .html files - one works and the other doesn't. The file that works contains: <html> <head></head> <body> <form method="post" action=&q ...

Vue.js: Exploring the issue of filtering using v-if and v-for

I'm encountering an issue with a computed property in Vue.js that is being used in a v-if statement. I've been struggling to find a solution or refactor the code. Any guidance on this matter would be greatly appreciated. Situation: Currently, I ...

The Jest mock for dates is completely ineffective and always ends up returning the constructor

beforeAll(() => { ... const mockedData = '2020-11-26T00:00:00.000Z' jest.spyOn(global, 'Date').mockImplementation(() => mockedData) Date.now = () => 1606348800 }) describe('getIventory', () => { ...

Simple server using node.js and express to host an HTML file and associated resources

I am currently experimenting with frontend development and need a basic web server to quickly start projects and serve files. Specifically, I have one index.html file along with some css/js/img files. I decided to work with Node.js and Express for this pur ...

Placing the template code underneath the existing code within the Handlebars layout.hbs file

I'm currently working on a project using Express Handlebars. I have a template called foo.hbs that contains some JavaScript code which I need to insert below the script tags in the layout.hbs file: <!DOCTYPE html> <html> <head> ...

Ways to position an image in the middle of a Div

I am currently working with PHP and Smarty, attempting to display a slideshow's images in the center of a specific div, but I am encountering difficulties achieving this. Below you will find the code snippet. Can anyone help me figure out what I migh ...

Limit the bootstrap datepicker to display only certain dates and today's date

I've integrated the Bootstrap Datepicker into my website. I need to customize it so that only specific dates are enabled, including today's date, and all other years, months, and days are hidden from the Datepicker. How can I achieve this? Furth ...

What is the reason behind the jQuery JSON parser requiring double escaping for backslashes?

I'm struggling to comprehend a strange aspect of the JSON data format. Here's the issue: I have a string with a Windows directory path, where backslashes are escaped. However, the jQuery JSON parser seems to require double escaping for some reas ...

`Optimizing Django by using multiple room relationships to save formset related models`

I need help with saving a formset that involves two models in a many-to-many relationship. When I open the page, two forms are displayed but after filling them out and clicking "Add", the fields for "phone" and "client_name" get cleared and the form is not ...