음악, 삶, 개발

컴포넌트간에 송신하기 : vuex 와 mitt 라이브러리 본문

개발 Web/Vue.js 공부방

컴포넌트간에 송신하기 : vuex 와 mitt 라이브러리

Lee_____ 2020. 12. 6. 23:21


< 참고자료 >

 

모든 Component 들간에 하나의 저장소 Vuex

npm mitt

import mitt from 'mitt'
 
const emitter = mitt()
 
// listen to an event
emitter.on('foo', e => console.log('foo', e) )
 
// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )
 
// fire an event
emitter.emit('foo', { a: 'b' })
 
// clearing all events
emitter.all.clear()
 
// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo)   // listen
emitter.off('foo', onFoo)  // unlisten

< Vuex 복습 >

 

컴포넌트가 서로 부모 자식 관계이건 나발이건

상관없이 어디에 있는 컴포넌트든지 서로 데이터를 주고 받을수없을까?

이때 우선적으로 사용하는것이 Vuex 이다.

Vuex 는 Vue 에서 사용할수있는 Global Variable 이다.

앞선 포스팅에서 다뤘었지만, 간단히 복습해보자.

 

먼저 vuex 를 사용하여 store 파일을 만들고,

/* store.js */

import { createStore }  from 'vuex'
 
export default createStore({

    state       : { text : 'Hello World!'},
    mutations   : {}

})

이 파일을 main.js 에 로딩하고,

/* main.js */

import { createApp }    from 'vue'
import App              from './components/App.vue'
import store            from './store/store.js'

createApp(App).use(store).mount('#app')

.vue 파일안에서 사용한다.

<!-- App.vue -->

<template>
    
    {{ text }}

</template>

<script>

    import { useStore } from 'vuex'

    export default {

        setup() {

            return { text : useStore().state.text }

        }
        
    }
    
</script>

< mitt 사용하기 >

 

mitt 라이브러리는 커스텀 이벤트를 만들어 송출, 수신할수있게해준다.

컴포넌트에서 어디든 mitt() 이 return 하는 emitter 에 접근가능하게하기위해,

vuex 의 state 에 저장해준다.

/* store.js */

import { createStore }  from 'vuex'
import mitt from 'mitt'
 
export default createStore({

    state       : { emitter : mitt() },

})

이제 .vue 에서 사용한다.

<!-- App.vue -->

<template>
    
    <button @mousedown="a">a</button>
    <button @mousedown="b">b</button>

</template>

<script>

    import { useStore } from 'vuex'

    export default {

        setup() {

            const emitter = useStore().state.emitter

            emitter.on('*', (type, e) => console.log(type, e)) // 모든 이벤트 수신

            function a() { emitter.emit('a : ', 'im a!') // 이벤트 송신 }
            function b() { emitter.emit('b : ', 'im b!') // 이벤트 송신 }

            return { a, b }

        }
        
    }

</script>

< mitt 를 왜 사용해야하는가? 모든걸 Vuex 의 state 에 변수로 넣으면 안되나? >

 

개발을 하다보면 생각보다 로컬로만 존재해야하는 데이터들이 많이 있다.

굳이 세세한 모든 컴포넌트의 로컬 데이터가 모두 global state 로 존재할 필요는 없는것이다.

두 컴포넌트가 송신하려할때, 이럴때는 그냥 mitt 을 사용하여 vuex 에서 이벤트로 송신하는것이

수월할수있다.