본문으로 바로가기

[Vue.js] Vue3 에서 컴포넌트간 통신하기 (mitt)

category Front End 2021. 1. 6. 16:47
  • Vu3 에서는 $on, $once, $off 를 사용하지 않음
  • $emit 은 parent component에 부착되어 trigger event handler API 로 여전히 사용됨
  • 'Eventbus'는 Vue 가 추천하는 공식적인 방법이 아님 
  • 'mitt' 와 같은 외부 라이브러리를 이용하여 이벤트 버스를 구현하자.

RFC (github.com/vuejs/rfcs/blob/master/active-rfcs/0020-events-api-change.md)

Vue 2 에서 $emit 은 parent component에 부착된 trigger event handler API 로,

event emitter API ($on, $off, $once) 를 tigger 하는데 사용될 수도 있다.

 

이것은 실제로 과부하이다. event emitter API 는 전형적인 구성요소간 data-flow가 아니다.

거의 사용되지 않으며, component를 통해 노출될 이유가 없다.


1. 설치

npm install --save mitt

 

2. 사용

 2.1) Vue의 globalPropoertise 로 emitter를 등록한다.

main.js 

import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt';

const emitter = mitt();
app.config.globalProperties.emitter = emitter'

app.mount('#app')

 

 

 2.2) event emit, emit 함수를 이용한다.

ChildA.Vue

<script>
export default { 
  data() {
    return {
    };
  },
  methods: {
    makeEvent() {
      var param = 1;
      this.emitter.emit("eventname", param);
    }
  }
};
</script>

 2.3) event recive, on 함수를 이용한다.

ChildB.Vue

<script>
export default {
  data() {
    return {
    };
  },
  mounted() { 
    this.emitter.on("event",
      msg => {console.log(msg)}
    );
};
</script>

2.4) composition api (Vue3) 를 이용할 경우, 아래와 같이 이용하면 된다.

import { getCurrentInstance } from 'vue'
export default{

   setup(){
      const internalInstance = getCurrentInstance(); 
      const emitter = internalInstance.appContext.config.globalProperties.emitter;

       ...
     },
  ...

}

 

 

v3.vuejs.org/guide/migration/events-api.html#_2-x-syntax

 

Events API | Vue.js

Events API breaking Overview $on, $off and $once instance methods are removed. Application instances no longer implement the event emitter interface. 2.x Syntax In 2.x, Vue instance could be used to trigger handlers attached imperatively via the event emit

v3.vuejs.org

ui.toast.com/weekly-pick/ko_20200804

 

Vue 3로 마이그레이션하기 위해 준비해야 할 것

필자는 이 글에서 Vue 3 베타 버전을 사용한 경험, 특히 Vue 3로 마이그레이션할 때 주의해야 할 점을 얘기하고자 한다. 만약 이미 Vue 2로 개발된 앱을 Vue 3로 업그레이드할 예정이라면 이 글이 유용

ui.toast.com

github.com/vuejs/rfcs/blob/master/active-rfcs/0020-events-api-change.md

 

vuejs/rfcs

RFCs for substantial changes / feature additions to Vue core - vuejs/rfcs

github.com

stackoverflow.com/questions/63471824/vue-js-3-event-bus

 

Vue.js 3 Event Bus

How to create Event Bus in Vue 3? In Vue 2, it was: export const bus = new Vue(); bus.$on(...) bus.$emit(...) In Vue 3, Vue is not a constructor anymore, and Vue.createApp({}); returns an object...

stackoverflow.com