Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vue can't receive subscribe to event from child component in to parent component

I have two components – parent and child. The child emits an event, which should trigger a console output in a parent component. However nothing is printed in console.

TestPage.vue:

<template>
  <div v-on:hidden="hiddenEvent">

    <TestComponent></TestComponent>
  </div>
</template>

<script>

import TestComponent from "@/app/test/TestComponent";
export default {
  name: "TestPage",
  components: {TestComponent},


  methods:  {
    hiddenEvent()  {
      console.log("hiddenEvent");
    }
  }
}
</script>

<style scoped>

</style>

TestComponent.vue:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<template>
  <div class="test-container" v-if="!isHidden"
        v-on:click="this.flip">
    {{this.text}}
  </div>
</template>

<script>
export default {
  name: "TestComponent",

  data() {
    return {
      text: "abc",
      isHidden: false
    }
  },

  methods:  {
    flip()  {
      this.isHidden = !this.isHidden;

      if (this.isHidden)  {
        this.$emit("hidden");
      } else  {
        this.$emit("revealed");
      }
    }
  }
}
</script>

<style scoped>

.test-container  {
  padding: 2em;

  background-color: #2EAC68;
}

</style>

When I click on the abc:

enter image description here

it disappears:

enter image description here

So I know the flip method is executed. However the parent’s hiddenEvent is not executed, because hiddenEvent is never printed to console.

What am I doing wrong? I need the parent TestPage to be able to react to the event emitted by the child TestComponent

>Solution :

You should use v-on:hidden="hiddenEvent" on TestComponent tag not on the wrapping div.

The

<TestComponent></TestComponent>

in TestPage.vue should be updated to:

<TestComponent v-on:hidden="hiddenEvent"></TestComponent>

See in sandbox

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading