[Vuejs]-Vue parent component unable to catch event emitted from the child

1👍

I noticed that the <script> tags are missing in your child component. Is that typo in your question? If they aren’t there then that could explain the issue you’re having.

Don’t use Camel Case for DOM attributes, which applies to emitters and custom events as well.

In your child, refactor to:

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

In your parent, refactor to:

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

Working Example via codesandbox.io. I had to open the preview in a new window/tab to display correctly.

1👍

You can use this as your alternative.

<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 will print");
            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>

0👍

These components are not nested, so Map is not actually the parent. Making it so causes some other issues. Not worh the hassle.

Leave a comment