[Vuejs]-Why wont the component respond to the custom event?

3👍

You could emit an event to parent from Main2 having as parameters this.counter and in the parent one receive that and pass it through props to Bottom

In Main2 :

this.$emit("emit-event-main2-counter",this.counter);

in the parent component :

  <template>
   <Main2 v-on:emit-event-main2-counter="sendToBottom"/>
   <Bottom :cntr="pcounter"/>
  ....
  </template>


  data:{
   pcounter:0
    },
  methods:{
       sendToBottom(c){
        this.pcounter=c
          }
      }

Bottom should have property called cntr

  props:["cntr"]

Bottom.vue

     <template>
      <div  class="Bottom" >
          bottom text and cntr ({{cntr}})
      </div>
    </template>

  <script>

    export default {
           props:["cntr"],
         data: () => {
             return {
                }
            },
       }
     </script>

2👍

If you want to use root events, you need to emit the event with this.$root.$emit() and also listen to the event on the root like this: this.$root.$on().

You should use it directly in the script part. Listen to the root event e.g. in the created() hook and then disable it with $off in the beforeDestroy() hook.


However, I wouldn’t encourage you to use $root events. It is usually better to communicate between the components like @BoussadjraBrahim proposed in his answer.

If you have a more complex application, it makes sense to take a look at Vuex and store the complete state in the Vuex store. By doing this, you can watch the global application state in the components and react if it changes. In this scenario, you would use the Vuex store instead of a root EventBus.

Leave a comment