Vue/Vuex
Vuex 핵심 컨셉(3) - 변이(mutations)
고코모옹
2021. 7. 1. 17:03
- 변이(mutations)
- Vuex Store에서 실제로 상태를 변경하는 유일한 방법
- 이벤트와 매우 유사
- 각 변이에는 문자열 타입, Handler 존재
- Handler 함수는 실제 상태 수정을 하는 곳이며, 첫번째 전달인자로 상태(state)를 받는다.
- Handler 함수를 직접 호출 할 수 없다.(이벤트 등록과 유사)
- Handler 함수를 호출하려면 해당 타입과 함께 store.commit을 호출
// store/index.js
const store = createStore({
state: {
count: 1
},
mutations: {
increment (state) {
// mutate state
state.count++
}
}
})
// Vue component에서 호출
store.commit('increment')
- payload를 가진 커밋
- store.commit에 payload라고 하는 추가 전달인자 사용 가능
- 대부분의 경우 payload는 여러 필드를 포함할 수 있는 객체여야 함
// store/index.js
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
// Vue component에서 호출
store.commit('increment', {
amount: 10
})
- 객체 스타일 커밋
- mutation을 커밋하는 또 다른 방법은 type 속성을 가진 객체를 직접 사용하는 것
- 전체 객체는 mutation Handler에 payload로 전달되므로 Handler는 동일하게 유지
// Vue component에서 호출
store.commit({
type: 'increment',
amount: 10
})
// store/index.js
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
- Vue의 반응성 규칙을 따르는 변이
- Vuex Store의 상태는 Vue에 의해 반응하므로, 상태를 변경하면 상태를 관찰하는 Vue component가 자동으로 업데이트 된다.
- Vuex mutation이 일반 Vue로 작업할 때 동일한 반응성에 대한 경고를 받을 수 있음을 의미
- 원하는 모든 필드에 앞서 저장소를 초기화 하는 것이 좋다.
- 객체에 새 속성을 추가할 때 다음 중 하나를 수행해야 한다.
- set 메소드 이용
Vue.set(obj, 'newProp', 123)
- spread 연산자를 사용하여 객체를 새로운 것으로 교체
state.obj = { ...state.obj, newProp: 123 }
- 변이 타입에 상수 사용
- 다양한 Flux 구현에서 변이 유형에 상수를 사용하는 것은 일반적인 패턴
- linter와 같은 툴링을 활용할 수 있으며 모든 상수를 단일 파일에 저장하면 공동 작업자가 전체 어플리케이션에서 어떤 변이가 가능한지 한눈에 파악 가능
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store/index.js
import { createStore } from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = createStore({
state: { ... },
mutations: {
// we can use the ES2015 computed property name feature
// to use a constant as the function name
[SOME_MUTATION] (state) {
// mutate state
}
}
})
- 변이는 무조건 동기적이어야 한다.
- 기억 해야할 한가지 중요한 규칙은 변이 핸들러 함수는 동기적 이어야 한다.
- 앱을 디버깅하고 devtool의 변이 로그를 보고 있다고 가정
- 기록된 모든 변이에 대해 devtool은 상태의 '이전' 및 '이후' 스냅샷을 캡처해야 한다.
- 변이 내의 비동기 콜백은 불가능
- 변이가 커밋 되었을 때 콜백은 아직 호출되지 않으며, 콜백이 실제로 호출 될 시기를 devtool이 알 수 있는 방법이 없다.
- 콜백에서 수행 된 모든 상태 변이는 본질적으로 추적할 수 없다.
mutations: { someMutation (state) { api.callAsyncMethod(() => { state.count++ }) } }
[ 참고자료 ]
https://next.vuex.vuejs.org/guide/mutations.html
Mutations | Vuex
Mutations The only way to actually change state in a Vuex store is by committing a mutation. Vuex mutations are very similar to events: each mutation has a string type and a handler. The handler function is where we perform actual state modifications, and
next.vuex.vuejs.org