Vue3/코딩애플 part3

[Vue/코딩애플/part3] 5. 멀리 있는 컴포넌트간 데이터 전송 시키기(mitt)

김나나_ 2024. 8. 5. 14:44

📌 mitt 라이브러리 설치

FilterBox.vue -> Container.vue -> App.vue 까지 데이터를 전송시켜보자

 

단순히 바로 위 상위 컴포넌트로 데이터를 전송할 때는 custom event 를 쓰면 됐었다.

상위상위 컴포넌트로 데이터로 전송시키고 싶을 때는 mitt 라이브러리를 이용할 수 있다.

 

 

1. 터미널을 열고 mitt 라이브러리 설치한다.

npm install mitt

 

package.json

 

2. main.js 에 mitt 라이브러리 등록

import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt'
let emitter = mitt();
let app = createApp(App)
app.config.globalProperties.emitter = emitter; // app.config.globalProperties : 글로벌한 변수보관함

app.mount('#app')

 

 

📌 app.config.globalProperties

app.config.globalProperties 은 글로벌한 변수보관함. 모든 컴포넌트들이 갖다 쓸 수 있다.

모든 컴포넌트에서 emitter 를 사용 시 mitt 라는 라이브러리가 동작한다고 생각하면 된다.

 

자주 쓰는 라이브러리가 있으면 app.config.globalProperties  여기다가 등록하면 된다.

ex) app.config.globalProperties.axios= axios;

이제 vue 파일에서 import axios 해욜 필요 없이 this.axios 로 사용 가능하다.

 

this.axios 로 써야함을 유의

 

main.js

 

App.vue

 

mitt 로 데이터 전송하기

1. this.emitter.emit() 로 데이터 발사하고

this.emitter.emit('작명', '데이터')

 

2. 수신하기

수신하고 싶은 컴포넌트 > mounted() {} 안에 this.emitter.on() 으로 수신하면 된다.

mounted 안에 작성하는 것이 관습이다.

this.emitter.on('작명', (data) ={}) // data : 이벤트 발사 할 때 들어있던 데이터

 

실습을 해보자

하위 컴포넌트에서 [버튼] 을 누르면 fire 함수를 통해 상위 컴포넌트로 데이터를 전송시킨다.

// FilterBox.vue (하위 컴포넌트)
// template 영역
<button @click="fire">버튼</button>


// script 영역
methods : {
    fire () {
      // 이벤트 발사
      this.emitter.emit('test', '데이터')
    }
  }

 

// App.vue (상위 컴포넌트)
 mounted() {
    this.emitter.on('test', (data) => {
      console.log('data > ', data)
    })
}

 

 

버튼을 누르면 콘솔로그를 통해 '데이터' 가 잘 전송되었음을 확인할 수 있다.

 

⚡ emitter 를 너무 많이쓰면 관리하기가 힘들어지니 vuex 를 쓰는 것이 낫다.