vuejs listening for event on component

2019-02-11 02:07发布

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

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-11 02:41

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

查看更多
登录 后发表回答