vuejs 监听组件上的事件 [英] vuejs listening for event on component

查看:43
本文介绍了vuejs 监听组件上的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();
        },
    }
}

在 Chrome 控制台上,我使用以下命令触发事件:

on the chrome console i am firing the event with:

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

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

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.

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

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(); 
    });
 }

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

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

-谢谢,Yeasir

推荐答案

看这个例子

index.js

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

这篇关于vuejs 监听组件上的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆