programing

vuejs 2.0의 재귀 구성 요소 통신

bestcode 2022. 8. 24. 23:56
반응형

vuejs 2.0의 재귀 구성 요소 통신

구성 요소 이름이 "custom Component"라고 가정합니다.

및 그 사용 예:

<custom-component class='parent'>
  <div v-if='someTruthyCondition'>
    <custom-component class='child'></custom-component>
  </div>
</custom-component>

someTruthyCondition'이 true util 3 컴포넌트가 생성되고 재귀가 정지된다고 가정합니다.

vue js에서 하위 custom Component에서 상위 custom Component로 통신하는 방법을 알고 싶습니다.

당신의 예시는 코드 냄새처럼 느껴지기 때문에 이것이 효과가 있을지는 잘 모르겠습니다만, 저는 이런 것을 시도해 본 적이 없습니다.이벤트를 사용할 수 있으며 하위 구성 요소가 생성될 때마다 이벤트를 부모에게 내보낼 수 있습니다.

https://vuejs.org/v2/guide/components.html#Using-v-on-with-Custom-Events

Vue.js 문서의 예에서는 다음과 같이 사용되고 있습니다.

<button-counter v-on:increment="incrementTotal"></button-counter>

그래서 자 컴포넌트는 이것을 내부에서created라이프 사이클 훅:

this.$emit('increment')

부모님 안에서 이 이벤트를 받을 때마다 숫자를 늘리면 되고 3에 도달하면 정지할 수 있습니다.v-for고리.

<custom-component class='child'></custom-component>

이게 먹힐지 어떨지는 모르겠지만, 머릿속에서는 내가 생각해낸 거야.

Vue.js에서는 기능을 소품으로 사용할 수 있습니다.React와 달리 Vue.js에는 자녀 간 통신을 위한 사용자 지정 이벤트가 있기 때문에 일반적인 패턴이 아닙니다.하지만 이런 경우에는 정말 유용합니다.

각 레벨에서 이벤트를 방출하는 것과 달리, 이 기능은 기능에 대한 동일한 참조만 전달하면 되므로 훨씬 단순하고 성능이 우수합니다.

이것 좀 봐.

테스트해 본 적은 없지만 이런 게 도움이 될 것 같아요.

main.filename:

window.Event = new Vue();

상위 요소:

mounted () {
    Event.$on('recursion', () => {
        this.recursion++;
    })
}

하위 요소:

created () {
    Event.$emit('recursion');
}

사용하다v-on="$listeners"부모에게 이벤트를 트리거하는 재귀 자식.

임의의 이벤트청취자를 컴포넌트의 첫 번째 콜에 접속하면 모든 재귀 콜컴포넌트에 접속할 수 있습니다.

<custom-component class='parent' @click="doSomething()">
  <div v-if='someTruthyCondition'>
    <custom-component class='child' v-on="$listeners"></custom-component>
  </div>
</custom-component>

이제 소비하는 컴포넌트에는doSomethingmethod - 임의의 재귀적 자녀에게 트리거됩니다.

언급URL : https://stackoverflow.com/questions/47012103/recursive-component-communication-in-vuejs-2-0

반응형