본문 바로가기

Vue.js

[Udemy Vue 완벽가이드 Section8] 105. 함수/메서드에서의 provide + inject

커스텀 이벤트에서도 provide, inject를 사용할 수 있을까?

할 수 있지만, 조금 다르게 구현된다.

 

커스텀 이벤트가 발생하면 트리거되는 메서드와 연결한다. App.vue의 activateTopic처럼.

<knowledge-base @select-topic="activateTopic"></knowledge-base>

물론, props를 사용해서 이런 메서드를 이벤트를 호출하는 아래 컴포넌트에 전달할 수도 있다.

 

 

# 함수/메서드 provide + inject 방법

1/ 함수를 사용하는 컴포넌트에서 selectTopic처럼 원하는 이름으로 함수명을 설정하자.

 

2/ 그런 다음, button 이벤트 리스너로 바인딩하자. selectTopic은 함수가 된다. click이 발생하면 실행되는 함수.

함수를 가리키고, provide, inject 메커니즘을 사용하여 이 함수를 value로서 가져오기를 원한다.

<buttton @click="selectTopic">Learn More</button>

<script>
 export default {
  inject: ['selectTopic'],
}
</script>

 

3/ App.vue에서 provide 하자.

topic을 활성화하는데 사용하는 함수가 있다. 바로 activateTopic 함수.

 

provide에 'selectTopic'키를 제공하자. 이게 바로 KnowledgeElement.vue에서 수신하는 key.

값은 methods의 this.activateTopic 메서드이다. pointer로 가리켜서 알려준다.

 

<template>
  <div>
    <active-element
      :topic-title="activeTopic && activeTopic.title"
      :text="activeTopic && activeTopic.fullText"
    ></active-element>
    <!-- <knowledge-base @select-topic="activateTopic"></knowledge-base> -->
    <knowledge-base></knowledge-base>
  </div>
</template>

//script
provide() {
  return {
    topics: this.topics,
    selectTopic: this.activateTopic,
  };
},
methods: {
  activateTopic(topicId) {
    this.activeTopic = this.topics.find((topic) => topic.id === topicId);
  },
},

 

 

activateTopic 메서드를 보면 id가 필요하다. 따라서 KnowledgeElement.vue에서 클릭했을 때 실행할 함수인 selectTopic을 포인터로 가리키는 곳에 id를 제공해야한다.

<buttton @click="selectTopic(id)">Learn More</button>

<script>
 export default {
  inject: ['selectTopic'],
}
</script>

 

이렇게 커스텀 이벤트를 emit하지 않고도 작동한다. 단지 방법이 다를 뿐이다.

 

** 출처: 모든 내용은 Udemy Vue-완벽가이드 강의를 기반으로 작성하였습니다.