IT이야기

vue 구성 요소가 이벤트를 전달하지 않습니다.

cyworld 2022. 5. 30. 22:04
반응형

vue 구성 요소가 이벤트를 전달하지 않습니다.

네스트된 컴포넌트가 3개 있습니다.

<parent @event="handle">
  <inbetween @event="$emit('event')">
    <child> // emits event
    </child>
  </inbetween>
</parent>

그래서 아이가 이벤트를 할 때 그 짜증나는 부분을 넣어야 해요.@event="$emit('event')"그렇지 않으면 부모가 이벤트를 수신하지 않습니다.

나는 그것이 그렇게 되지 않기를 바란다.그게 뭐가 잘못됐을까?

이건 사실 의도적인 거예요.한 컴포넌트의 코드를 보면 이벤트를 듣고 있는 것을 알 수 있습니다.그 후 템플릿을 보고 이벤트가 어디서 발생하는지 확인할 수 있습니다.이벤트가 임의의 깊이의 컴포넌트에 도달할 수 있는 경우 이벤트가 트리거되는 방법과 장소를 파악하는 것이 어려워집니다.

하지만 Vue는 그 방법을 통해 당신이 원하는 것을 할 수 있는 방법이 있었습니다.$broadcast그리고.$dispatch그리고 그들은 결국 여기서 말한 이유로 제거되었다.이 문서는 글로벌 이벤트 버스나 Vuex 등의 중앙 집중식 상태 관리 솔루션과 같은 가능한 솔루션과 함께 그 이유를 설명합니다.

네, 그렇게 작동해야 합니다.이벤트는 자녀에서 부모로만 진행되며 자녀에서 조부모로 진행되지 않습니다.따라서 하위 구성 요소와 중간 구성 요소 모두에서 이벤트를 내보내야 합니다.

이 방법을 사용하지 않으려면 이벤트 버스를 사용할 수 있습니다.

https://medium.com/ @subejsabrickis/sube-medium-com-subrickis-create-vue-subrickis-create-eventbus-to-cdc11cd59860

alligator.io/vuejs/global-event-bus

Vue 사용자 지정 이벤트는 버블이 발생하지 않습니다.

복잡한 경우 상위/자매 통신을 처리하는 권장 방법은 Vuex를 사용하는 것입니다.간단한 요구 사항이 있는 경우 이벤트 허브로 사용할 Vue 인스턴스를 생성할 수 있습니다.

글로벌 변수를 만듭니다.

var eventHub = new Vue(); // use a Vue instance as event hub

컴포넌트에서 사용하는 이벤트를 내보내려면:

eventHub.$emit('myevent', 'some value');

그리고 이 이벤트를 들으려면 모든 컴포넌트에서 다음 작업을 수행합니다.

eventHub.$on('myevent', (e) => {
    console.log('myevent received', e)
});

데모:

var eventHub = new Vue(); // use a Vue instance as event hub

Vue.component('parent', {
    template: "#parent-tpl",
    created() {
      eventHub.$on('event', (e) => {
      	console.log('event received at parent! value:', e);
      });
    }
});
Vue.component('inbetween', {
    template: "#inbetween-tpl"
});
Vue.component('child', {
    template: "#child-tpl",
    methods: {
      emitEvent() {
        eventHub.$emit('event', 123);
      }
    }
});

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  }
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

<template id="parent-tpl">
    <div>
        <inbetween></inbetween>
    </div>
</template>
<template id="inbetween-tpl">
    <div>
        <child></child>
    </div>
</template>
<template id="child-tpl">
    <div>
      <h1>I'm the child</h1>
      <button @click="emitEvent">Trigger EVENT</button>
    </div>
</template>

<div id="app">
  <p>{{ message }}</p>
  <parent></parent>
</div>

주의: 전용 인스턴스를 이벤트 허브로 만드는 것이 고객의 환경에서 복잡한 경우 대체할 수 있습니다.eventHub와 함께this.$root(컴포넌트 내부)를 사용하여 자체 Vue 인스턴스를 허브로 사용합니다.

언급URL : https://stackoverflow.com/questions/49568756/vue-component-is-not-passing-events-through

반응형