source

구성 요소에서 이벤트를 수신하는 vuej

goodcode 2022. 8. 8. 20:03
반응형

구성 요소에서 이벤트를 수신하는 vuej

콘솔에서 내보내는 커스텀컴포넌트에서 플래시 이벤트를 수신할 수 없습니다.내 컴포넌트는 다음과 같습니다.

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

크롬 콘솔에서 이벤트를 실행합니다.

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

vue devtools 탭에서 볼 수 있듯이 이벤트가 발생합니다.그러나 이벤트를 감지하면 컴포넌트가 표시되어야 하지만 표시되지 않습니다.

단, components created() 메서드 내의 글로벌이벤트 버스에서 청취자를 피기백하면 동작합니다.

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

이벤트 리스너를 컴포넌트 자체의 이벤트 속성 내에 등록하려면 어떻게 해야 합니까?

-고마워, 예시르

예를 보다

eventbus가 index.display에 작성되었습니다.

Vue.prototype.$vueEventBus = new Vue()

리스너 온(컴포넌트/eventBus/eventBus.vue 참조)

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

import 이벤트(컴포넌트/eventBus/childEventBus.vue 참조)

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

앱 페이지 https://3xyx386q65.codesandbox.io/eventBus

언급URL : https://stackoverflow.com/questions/47754830/vuejs-listening-for-event-on-component

반응형