vuejs在组件上侦听事件

Yea*_*der 4 javascript events vuejs2

我无法捕获我从控制台发出的自定义组件上的flash事件.这是我的组件:

/* 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();
        },
    }
}
Run Code Online (Sandbox Code Playgroud)

在Chrome控制台上,我用以下方法解雇了这个事件:

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

事件正在解雇,因为我可以在vue devtools选项卡上看到.但是在捕获事件时,组件应该变得可见,而不是.

但是,如果我在组件created()方法内的全局事件总线上搭载监听器,它就可以工作.

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

如果我希望事件监听器在组件本身的events属性中注册,我该怎么办?

谢谢,Yeasir

小智 6

看这个例子

index.js中创建的eventbus

Vue.prototype.$vueEventBus = new Vue()
Run Code Online (Sandbox Code Playgroud)

监听器(参见components/eventBus/eventBus.vue)

created() {
  this.$vueEventBus.$on('message-in', this.newMessage)
},
beforeDestroy() {
  this.$vueEventBus.$off('message-in')
}
Run Code Online (Sandbox Code Playgroud)

发出事件(请参阅components/eventBus/childEventBus.vue)

methods: {
  newMessage(something) {
    this.$vueEventBus.$emit('message-in', something)
  }
}
Run Code Online (Sandbox Code Playgroud)

应用页面https://3xyx386q65.codesandbox.io/eventBus