1. store.js 에 state 수정 방법을 정의한다.
2. 수정하고 싶으면 store.js 에 부탁한다.
state 수정 방법을
mutations : { } 에 정의하면 된다.
// store.js
import { createStore } from 'vuex'
const store = createStore({
state() {
return {
// state 보관은 여기에
name : 'kim',
age : 20
}
},
mutations : {
// state 수정 방법 정의
}
})
export default store
'kim' 이라는 name 을 'park' 으로 변경하고 싶다면 다음과 같이 정의한다.
// store.js
mutations : {
// state 수정 방법 정의
changeNm (state) {
state.name = 'park'
}
}
this.name 이 아니라, state.name 으로 접근한다는 것에 주의한다.
(첫번째 파라미터는 위에 정의한 state를 의미)
이제 store.js 에 정의한 함수를 호출하려면
$store.commit(함수명)
<button @click="$store.commit('changeNm')"> store 데이터 변경하기</button>
버튼을 누르면 kim 에서 park 으로 잘 변경되고 있다.
🔎 store.js 의 장점
- state 변경은 store.js 만 한다 => 이제 state 이상하면 store.js 를 살피면 된다 (디버깅 편리)
mutations 에 데이터를 보내고 싶다면/.
<button @click="$store.commit('changeAge', 10)"> 나이 변경하기</button>
changeAge 라는 age 를 증가시켜주는 함수에 10이라는 데이터를 보내고 싶다면 increaseAge 함수에 파라미터를 추가하면 된다.
increaseAge (state, data) {
state.age += data;
}
data 에 10이라는 숫자가 들어온다.
'Vue3 > 코딩애플 part3' 카테고리의 다른 글
[Vue/코딩애플/part3] 9. methods와 comptued 차이점 / vuex - mapState, mapMutatiuons (0) | 2024.08.05 |
---|---|
[Vue/코딩애플/part3] 8. vuex - actions/dispatch (ajax, 오래 걸리는 작업 실행하기) (0) | 2024.08.05 |
[Vue/코딩애플/part3] 6. vuex 설치 (0) | 2024.08.05 |
[Vue/코딩애플/part3] 5. 멀리 있는 컴포넌트간 데이터 전송 시키기(mitt) (0) | 2024.08.05 |
[Vue/코딩애플/part3] 4. props 대신 slot (0) | 2024.08.05 |