[Vue] Vuex
Vuex
컴포넌트 별로 데이터를 주고 받기 어렵다.
하위 컴포넌트 전송은 props, 상위 컴포넌트로의 전송은 custom event, mitt 라이브러리를 써야 한다.
이 때 쓸 수 있는 라이브러리가 Vuex다.
Vuex는 모든 컴포넌트들이 데이터를 공유할 수 있는 하나의 자바스크립트 파일이다.
컴포넌트와 데이터가 많을 때 Vuex를 쓰면 편리하지만, 간단한 프로젝트를 할 때에는 props를 쓰는게 더 낫다.
1. 설치하기
https://vuex.vuejs.org/installation.html
1
2
3
(sudo) npm install vuex@next
// or
yarn add vuex@next
2. 셋팅하기
데이터를 저장할 js파일을 만들고, 예제코드를 넣는다.
https://vuex.vuejs.org/guide/#the-simplest-store
@/assets/store.js
1
2
3
4
5
6
7
8
9
10
11
12
13
(store.js)
import { createStore } from "vuex";
const store = createStore({
state () {
return {
name: 'kim'
}
},
})
export default store;
3. 등록하기
index.js 파일에서 store파일을 import하고 app.use(store)로 등록해준다.
1
2
3
4
5
6
7
8
9
10
11
12
13
(index.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; // global value
import store from '@/assets/store.js' // 추가
app.use(store).mount('#app') // use(store)추가
이제 store.js에 등록된 state들은 모든 컴포넌트에서 사용이 가능하다.
4. 데이터 꺼내 쓰기
$store.state.변수명
1
<h4>안녕 {{ $store.state.name }}</h4>
5. 데이터 변경하기 1
1
<button type="button" @click="$store.state.name = '박'">버튼</button>
- Vuex 국룰 : 컴포넌트 안에서 직접 수정하기 금지!
위와 같이 간단하게 수정이 가능하지만, 컴포넌트 안에서 직접 수정은 이렇게 하면 안된다.
이렇게 작업하게 되면 데이터 추적이 어려워지기 때문이다.
Vuex에서 데이터를 수정하고 싶으면, 미리 store.js에 수정 방법을 정의해두고, 그 방법을 컴포넌트에서 소환하여 수정해야 한다.
6. 데이터 변경하기 2
데이터 변경을 할 때에는 store.js에 변경을 부탁하자
6-1. store.js에 state 수정 함수 정의
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(store.js)
import { createStore } from "vuex";
const store = createStore({
state () {
return {
name: 'kim'
}
},
mutations: { // state 수정 방법 정의 하는 곳
changeName(state){ // state는 위에 있는 state()를 의미한다.
state.name = 'park';
}
}
})
export default store;
6-2. store.js에 정의 된 함수 실행
$store.commit(‘함수명’)
1
2
3
4
(App.vue)
<h4>안녕 {{ $store.state.name }}</h4>
<button type="button" @click="$store.commit('changeName')">버튼</button>
@숙제
App.vue 어딘가에 age 데이터 바인딩
버튼을 만들고 그걸 누르면 age가 +10 되게 한다.
$store.commit(‘함수명’, 전달할데이터)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
(store.js)
import { createStore } from "vuex";
const store = createStore({
state () {
return {
name: 'kim',
age: 20
}
},
mutations: { // state 수정 방법 정의 하는 곳
changeName(state){ // state는 위에 있는 state()를 의미한다.
state.name = 'park';
},
addAge(state, data){
state.age += data;
}
}
})
export default store;
1
2
3
4
(App.vue)
<h4>나이는 {{ $store.state.age }}</h4>
<button type="button" @click="$store.commit('addAge', 10)">나이를 올리자</button>