vuejs在组件上侦听事件

时间:2017-12-11 14:14:32

标签: 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();
        },
    }
}
在chrome控制台上的

我用以下方式触发事件:

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

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

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

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

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

-Thanks,Yeasir

1 个答案:

答案 0 :(得分:5)

看这个example

index.js

中创建的eventbus
Vue.prototype.$vueEventBus = new Vue()

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

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

发出事件(参见 components / eventBus / childEventBus.vue

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

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

相关问题