상위 컴포넌트에 데이터 전송이 아닌 먼 컴포넌트에 데이터 전송할 일이 가끔 있다.
컴포넌트-custom event->상위 컴포넌트-custom event->상위 컴포넌트로 하면 코드가 너무 길어진다.
이런 상위상위 컴포넌트에 데이터를 쉽게 전달하기 위해 mitt라는 라이브러리를 다운받아 적용해보자!
상위 컴포넌트에 데이터 전달을 쉽게 도와주는 라이브러리
npm install mitt
yarn add mitt
// main.js
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.mount('#app') import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt'
let emitter = mitt();
let app = createApp(App);
// app.config.globalProperties
// 모든 컴포넌트에서 사용할 수 있는 변수를 등록할 수 있게 도와주는 일종의 object 자료(글로벌 변수 보관함)
// => 변수보관함에 {emitter:emitter}를 추가한것과 같다!
app.config.globalProperties.emitter = emitter;
app.mount('#app')
this.emitter.emit('이벤트명 작성', '보낼 데이터')
! 보통 수신하는 코드는 mounted()안에 적는다.
this.emitter.on('이벤트명 작성', (보낸 데이터)=>{ 데이터 수신시 실행하는 코드 })
// 하위 컴포넌트
<template>
<button v-on:click="clickMe">버튼</button>
</template>
<script>
export default{
methods:{
clickMe(){
this.emitter.emit('발사','데이터')
}
}
</script>
// 상위 컴포넌트
<script>
export default{
mounted:{
this.emitter.on('발사',(e)=>{
console.log(e) // 데이터
})
)
}
</script>
근데 많이 사용하면 관리가 힘들어진다.
이름이 겹치거나 어디서 보낸 데이터인지 관리해야하기 때문
그럴때는 Vuex 사용해보자
- props와 custom event로 데이터를 주고받는게 힘들면 사용
- vue 파일과 데이터가 너무 많으면 사용하는 라이브러리
Vuex를 쓰면 데이터를 한곳에서 저장하고 관리해주기 때문에, 수정하는 방법도 쉽다.(단 컴포넌트 안에서 직접 수정 금지!)
Vuex
npm install vuex@next
yarn add vuex@next
src 폴더 안에 store.js를 만든다.(store로 만드는게 관습적이다)// store.js
import { createStore } from 'vuex'
const store = createStore({
state(){
return {
}
},
})
export default store
store.js 파일을 main.js에 등록// main.js
import store from './store.js'
app.use(store).mount('#app')
그럼 store.js의 state에 저장한 데이터들은 모든 컴포넌트가 사용할 수 있다.
vue파일에서 {{ $store.state.데이터명 }}
단 함수나 mounted에서 쓰려면 {{ this.$store.state.데이터명 }}
// store.js
import { createStore } from 'vuex'
const store = createStore({
state(){
return {
name : 'kim'
}
},
})
export default store
// app.vuee
<h3>{{ $store.state.name }}</h3>
Vuex에서는 컴포넌트 안에서 수정하는걸 금지한다.
오류가 날때 어떤 컴포넌트에서 난 오류인지 추적하기 힘들기 때문이다.
state 수정은 store.js만 할 수 있게 코드를 짜놓는걸 추천한다!
👉 mutations 이라는 object 항목을 만들어 수정방법(함수)를 정의한다!
(state안에 데이터를 사용하려면 state를 받아서 state.데이터명 으로 접근해야한다)
// store.js
import { createStore } from 'vuex'
const store = createStore({
state(){
return {
데이터 : 1
}
},
mutations():{
데이터수정함수(){
// 데이터 수정 코드
}
}
})
export default store
버튼을 누르면 숫자가 1씩 증가하는 수정을 해야한다고 가정해보자
mutations에서 만든 함수는 $store.commit('함수명',보낼데이터) 로 사용할 수 있다.
// app.vue
// 버튼을 누르면 store의 plus함수가 실행된다
<button @click="$store.commit('plus',0)">{{ $store.state.num[0] }}버튼</button>
<button @click="$store.commit('plus',1)">{{ $store.state.num[1] }}버튼</button>
<button @click="$store.commit('plus',2)">{{ $store.state.num[2] }}버튼</button>
// store.js
import { createStore } from 'vuex'
const store = createStore({
state(){
return {
num: [0,0,0],
}
},
mutations():{
plus(state,data){
state.num[data]++;
}
}
})
export default store
