javascript vuejs 监听组件上的事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47754830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:34:23  来源:igfitidea点击:

vuejs listening for event on component

javascripteventsvuejs2

提问by Yeasir Arafat Majumder

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

我无法捕捉到我从控制台发出的自定义组件上的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();
        },
    }
}

on the chrome console i am firing the event with:

在 chrome 控制台上,我用以下方式触发事件:

/* 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.

该事件正在触发,因为我可以在 vue devtools 选项卡上看到。但是在捕获事件后,组件应该变得可见,而事实并非如此。

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

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

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 eventsproperty of the component itself?

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

-Thanks, Yeasir

-谢谢,耶西尔

回答by Volodymyr Symonenko

look this example

看这个例子

eventbus created in index.js

index.js 中创建的事件总线

Vue.prototype.$vueEventBus = new Vue()

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

监听器(参见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)

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

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

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

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