programing

Vue.js 2의 컴포넌트에서 이벤트 청취자에 액세스할 수 있습니까?

goodcopy 2022. 11. 26. 12:54
반응형

Vue.js 2의 컴포넌트에서 이벤트 청취자에 액세스할 수 있습니까?

Vue.js(2)에 다음과 같은 커스텀 컴포넌트가 있습니다.

Vue.component("modal-panel", {
    props: {
        id: {
            required: true
        },
        title: {} ,
        size: {
            validator: function(value) {
                return !value || value=="lg" || value=="sm";
            }
        }, 
        confirmLabel: {
            "default": "Yes",
        }, 
        closeLabel: {
            "default": "No"
        },
        confirm: {
            type: Function
        }
    },
    //...
    template: `
        //...
        <button type="button" class="btn btn-primary confirm" data-dismiss="modal" v-on:click="$emit('confirm')" v-if="confirm">{{confirmLabel}}</button>
        //...
    `
}

그리고 이것은 컴포넌트를 사용한 코드입니다.

<modal-panel title="New User" id="userModal" @confirm="doSomething">...</modal-panel>

컴포넌트 코드에서 볼 수 있듯이 소품에는 컨펌이 삽입되어 있으며 템플릿 내의 버튼 코드에는 컨펌 리스너 부착 여부에 따른 조건부 렌더링이 있습니다.그러나 단추는 렌더링되지 않습니다.컴포넌트 돔과 속성을 확인했지만 그런 정보는 없습니다.

vue.js의 컴포넌트에 특정 청취자가 연결되어 있는지 여부에 따라 조건부 렌더링을 할 수 있습니까?

감사해요.

Vue 2.4 이후 Vue 컴포넌트에는$listeners소유물.

부모 범위 v-on 이벤트 리스너를 포함합니다(.native 한정자 없음).

여기에 기재되어 있습니다.부모가 특정 이벤트를 재생하고 있는지 여부를 판별하려면$listeners소유물.


원답

일반적으로 컴포넌트가 스스로 손을 뻗어 사물을 결정하는 것은 좋지 않습니다.

그 대신, 고객님께 권하고 싶은 것이 있습니다.confirm콜백 속성함수를 속성으로 전달할 수 있습니다.그런 다음 콜백을 받았는지 여부에 대한 버튼을 표시하거나 숨길 수 있습니다.

Vue.component("modal",{
  props:["confirm"],
  template: `
    <div>
      <h1>Modal</h1>
      <button v-if="confirm" @click="confirm">Confirm</button>
    </div>
  `
})

.

편집

지정된 이벤트에 대한 구성 요소에 정의된 처리기가 있는지 확인할 수 있지만, 이 처리기를 사용하려면 내부 Vue 속성을 검사해야 하므로 사용자 자신의 책임으로만 사용해야 합니다.

Vue.component("modal",{
  template: `
    <div>
      <h1>Modal</h1>
      <button v-if="hasConfirmHandler" @click="$emit('confirm')">Confirm</button>
    </div>
  `,
  computed:{
    hasConfirmHandler(){
      return !!this._events["confirm"]
    }
  }
})

_events부모로부터 핸들러가 정의되어 있는 경우, 컴포넌트의 속성에는 핸들러가 포함됩니다.

.

기능을 바인딩해야 합니다.v-bind또는:그냥 끈으로 전달하는 게 아니라사용방법:confirm구문:

<modal-panel title="New User" id="userModal" :confirm="doSomething"></modal-panel>

다음으로 컴포넌트 템플릿에서는v-on:click="confirm()":

<button type="button" class="btn btn-primary confirm" data-dismiss="modal" 
  v-on:click="confirm()" 
  v-if="confirm">
  {{confirmLabel}}
</button>

언급URL : https://stackoverflow.com/questions/43574377/is-it-possible-to-access-event-listeners-from-component-in-vue-js-2

반응형