source

Vue.js Functional 컴포넌트에서 이벤트를 내보내는 방법

factcode 2022. 8. 24. 23:49
반응형

Vue.js Functional 컴포넌트에서 이벤트를 내보내는 방법

질문의 제목으로thiscontext는 기능 컴포넌트에서 사용할 수 없습니다.그래서 이벤트를 내보내야 한다면 어떻게 해야 하나요?

예를 들어 아래 코드 스니펫은 다음과 같습니다.

<template functional>
    <div>
        <some-child @change="$emit('change')"></some-child>
    </div>
</template>

기능 컴포넌트에는this문맥과 그에 따른$emit사용할 수 없습니다.어떻게 하면 이 이벤트를 망칠 수 있을까요?

자 컴포넌트

<template functional>
  <button @click="listeners['custom-event']('message from child')">
    Button from child
  </button>
</template>

상위 컴포넌트

<template>
  <div>
    <child-component @custom-event="call_a_method" />
  </div>
</template>

코드 앤 박스에서의 동작 확인

vue 인스턴스에서 이벤트를 내보내시겠습니까?

export default {
  functional: true,
  render(createElement, { listeners }) {
    return createElement(
      "button",
      {
        on: {
          click: event => {
            const emit_event = listeners.event_from_child;
            emit_event("Hello World!Is this the message we excpected? :/");
          }
        }
      },
      "Pass event to parent"
    );
  }
};

여기에서도 샌드박스 예제를 참조하십시오.

는 문서 "자 요소/컴포넌트에 Attribute 및 Events to Child Elements/Components:

템플릿 기반 기능 컴포넌트를 사용하는 경우 Atribute 및 Listener도 수동으로 추가해야 합니다.개개의 콘텍스트 컨텐츠에 액세스 할 수 있기 때문에,data.attrsHTML 속성을 전달하고listeners(의 에일리어스)data.on이벤트 청취자를 전달합니다.

가장 기본적인 수준에서는 다음과 같이 모든 청취자를 위임할 수 있습니다.

<some-child v-on="listeners"></some-child>

바인드만 하고 싶은 경우change리스너:

<some-child @change="listeners.change"></some-child>

하지만 이것은 실패할 것이다.listeners.change정의되지 않았거나 정의되지 않았습니다(기능 컴포넌트에는 제공되지 않음).

없는 상황에 대처할 필요가 있는 경우changelistener를 사용하면 다음과 같이 할 수 있습니다.

<some-child @change="listeners.change && listeners.change($event)"></some-child>

그렇지 않으면 렌더링 함수를 손으로 쓰는 것으로 해결되어야 할 것입니다. 왜냐하면 조건부로 할당하는 것은 불가능하다고 생각하기 때문입니다.change경청자.<some-child>사용할 수 있습니다. (혹은 할 수 있을까요?잘 모르겠어요.)

이벤트 리스너를 조건부로 전달하려면 다음과 같이 기능 컴포넌트 템플릿 내에서 수행할 수 있습니다.

v-on="listeners.change ? { change: listeners.change } : null"

청취자를 조건부로 접속하는 문제는 여기서 설명합니다.

jsx가 있는 컴포넌트:

export default {
  name: "MyText",
  functional: true,// functional component
  props: {
    value: {
      type: [String, Number],
      default: ""
    }
  },
  render(h, context) {
    const { props } = context;

    // with jsx

    // return (
    //   <button
    //     onClick={() => {
    //       console.log(context.listeners);
    //       context.listeners.input(Math.random().toString(36));
    //       context.listeners["my-change"](Math.random().toString(36));
    //       context.data.on.change(Math.random().toString(36));
    //     }}
    //   >
    //     {props.value}
    //   </button>
    // );

    // or use h function
    return h(
      "h1",
      {
        on: {
         // emit some event when click h1
          click: () => {
            // has value prop has has input event auto
            // event name come  what event u listen in parent component
            console.log(context.listeners);
            context.listeners.input(Math.random().toString(36));
            context.listeners["my-change"](Math.random().toString(36));
            context.data.on.change(Math.random().toString(36));
          }
        }
      },
      props.value
    );
  }
};

conext.listeners에 대한 가명일 뿐입니다.context.data.on부모 컴포넌트에서는 리슨해야 합니다.my-change그리고.change, 또는 에러가 있습니다.

컴포넌트 내의 이벤트명은 부모 컴포넌트에서 수신하는 이벤트를 가져옵니다.

<MyText
  v-model="value"
  @change="change"
  @my-change="myChange"
  @u-change="uChange"
/>

vue 2.6.11은 정상적으로 동작합니다.

온라인으로 코드 및 상자 보기

부모:

<Child @onFunction="handleFunction">

그리고 이것은 자 컴포넌트입니다.

어린아이

<template functional>
    <div>
        <some-child @change="execute"></some-child>
    </div>
</template>

methods:
  execute(){
   @emit("onFunction")
  }

언급URL : https://stackoverflow.com/questions/50288996/how-to-emit-an-event-from-vue-js-functional-component

반응형