반응형
이거 보세요.컴포넌트 A의 $emit('eventName') 이벤트는 이를 트리거하지 않습니다.컴포넌트 B의 $on('eventName', callbackFunc), 핸들러를 잘못 배치했습니까?
기본적으로 생성 시 이벤트를 트리거하는 컴포넌트와 생성된 컴포넌트를 카운트하는 특수한 "카운터" 컴포넌트가 있습니다.이 두 번째 컴포넌트는 첫 번째 컴포넌트와 병렬로 존재합니다.그러나 앱을 실행하려고 하면 카운터 컴포넌트 자체만 카운트되고 거기서 트리거되는 생성 이벤트만 검출되는 것 같습니다.
이걸 옮기려고 했어요mounted() 등의 다른 라이프 사이클 훅에 대한 $on() 조작이 실패하였습니다.
컴포넌트 A:
Vue.component('counter-component',{
template: `
<div class="card">
<div class="card-header">
Components:
</div>
<div class="card-body">
<p>Count: {{ totalCount }}</p>
<p>Enabled Count: {{ totalEnabledCount }}</p>
<p>Diabled Count: {{ totalDisabledCount }}</p>
</div>
</div>`,
created(){
this.$on('component-created', this.componentCreated),
this.$on('component-disabled', this.componentDisabled),
this.$on('component-enabled', this.componentEnabled),
this.$emit('component-created', 'counter-component');
},
data(){
return {
totalCount: 0,
totalDisabledCount: 0,
}
},
computed: {
totalEnabledCount(){
return this.totalCount - this.totalDisabledCount;
},
},
methods: {
componentCreated(data){
this.totalCount++;
},
componentDisabled(data){
this.totalDisabledCount++;
},
componentEnabled(data){
this.totalDisabledCount--;
}
}
});
컴포넌트 B:
Vue.component('regular-component',{
template: `
<div class="my-2">
<div class="card" v-show="isVisible">
This is visible
</div>
<div class="card" v-show="!isVisible">
This is invisible
</div>
</div>`,
created(){
this.$emit('component-created', 'message-component');
},
data: () => {
return ({
isVisible: true,
});
},
methods: {
toggleVisibility(){
this.isVisible = !this.isVisible;
if(this.isVisible){
this.$emit('component-enabled','message-component');
} else {
this.$emit('component-disabled','message-component');
}
}
},
});
두 컴포넌트 모두 계산될 것으로 예상했는데 안타깝게도 핸들러가 포함된 컴포넌트만 계산됩니다.
글로벌 이벤트버스가 있어서emit
구독해 주세요.
Vue에서는 기본적으로 그렇지 않습니다. 대신 Vue는 이벤트가 하위에서 상위로 전송되고 속성이 상위에서 하위로 전달되는 엄격한 계층 방식을 사용합니다.형제 구성 요소 간의 상호 작용은 기본적으로 의도되지 않습니다.
이 경우 올바른 접근법은 이벤트를 듣고 이벤트를 진행하는 부모 컴포넌트를 도입하는 것입니다.totalCount
상태 표시 및 카운터 디스플레이 컴포넌트에 속성으로 전달합니다.
<parent>
<regular-component v-on:component-created="totalCount++"/>
...
<counter-component v-bind:count="totalCount"/>
</parent>
사용하세요vuex
스파게티 코드의 양을 줄이는 데 도움이 됩니다.
언급URL : https://stackoverflow.com/questions/58098582/vue-this-emiteventname-events-in-component-a-are-not-triggering-this-one
반응형
'programing' 카테고리의 다른 글
@QueryParam vs @PathParam을 사용하는 경우 (0) | 2022.08.28 |
---|---|
C 프리프로세서는 순환 의존관계를 어떻게 처리합니까? (0) | 2022.08.17 |
C에서 nanosleep()을 사용하는 방법'tim.tv_sec'과 'tim.tv_nsec'이 뭐죠? (0) | 2022.08.17 |
문자열을 한 줄씩 읽다 (0) | 2022.08.17 |
C에서 true와 false 사용 (0) | 2022.08.17 |