Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs listening for event on component

I am unable to catch the flash event on my custom component that i am emitting from the console . Here is my component:

/* file flash.vue */

<template>
  <span :class="type" class="alert flash-alert" v-show="show">
    {{ body }}
  </span>
</template>

<script>
  export default {
    props: ['type','message'],
    data() {
        return {
            body: this.message,
            show: false,
        };
    },

    created() {
        if(this.body)
        {
            this.showComp();
            this.hide();
        }
    },

    methods: {
        showComp: function(){
            this.show = true;
        },

        hide: function()
        {
            var vm = this;
            setTimeout(function() {
                vm.show = false;
            },2000);
        },
    },

    events: {
        flash: function(newMessage) {
            this.body = newMessage;
            this.showComp();
        },
    }
}

on the chrome console i am firing the event with:

/* from console */
window.vueEventBus = new Vue();
window.vueEventBus.$emit('flash','my message');

the event is firing as i can see that on the vue devtools tab. But upon catching the event the component should become visible, which is not.

However, if i piggyback the listener on the global event bus inside the components created() method, it works.

created() {
  window.vueMessageBus.$on('flash',newMessage => {
      this.body = newMessage;
      this.showComp(); 
    });
 }

What should i do if i want the event listener to be registered inside the events property of the component itself?

-Thanks, Yeasir

like image 326
Yeasir Arafat Majumder Avatar asked Dec 11 '17 14:12

Yeasir Arafat Majumder


1 Answers

look this example

eventbus created in index.js

Vue.prototype.$vueEventBus = new Vue()

listener on (see components/eventBus/eventBus.vue)

created() {
  this.$vueEventBus.$on('message-in', this.newMessage)
},
beforeDestroy() {
  this.$vueEventBus.$off('message-in')
}

emit event (see components/eventBus/childEventBus.vue)

methods: {
  newMessage(something) {
    this.$vueEventBus.$emit('message-in', something)
  }
}

app page https://3xyx386q65.codesandbox.io/eventBus

like image 137
Volodymyr Symonenko Avatar answered Oct 12 '22 03:10

Volodymyr Symonenko