티스토리 뷰
1. Strict Mode
strict 모드를 사용하기 위해서는 strict: true
를 Vuex의 store를 만들 때 추가만 하면 됩니다.
const store = new Vuex.Store({
// ...
strict: true
})
strict 모드에서는 state가 mutation 핸들러 외부에서 변경 될 때 마다 오류를 발생 시킵니다.
배포시 strict 모드를 꺼야 합니다. strict 모드는 부적절한 state의 변경을 감지하기 위해 state 트리를 관찰하기 때문에, 성능 저하가 발생합니다. 성능 이슈를 해결하기 위해서는 배포 버전에서는 strict 모드를 꺼야 합니다.
const store = new Vuex.Store({
// ...
strict: process.env.NODE_ENV !== 'production'
})
2. Form Handling
strict 모드로 Vuex를 사용하는 경우 v-model
을 사용하는 것이 까다로울 수 있습니다.
<input v-model="obj.message">
obj
가 store에서 객체를 반환하는 computed
속성이라면 v-model
은 사용자의 입력이 있을 때, obj.message
를 직접 변경하려고 합니다. 하지만 strict 모드에서는 state의 변경이 mutation 핸들러 내부에서 수행되지 않기 때문에 오류를 발생시킵니다. 이러한 문제점을 해결하는 2가지 방법에 대해 이야기 하도록 하겠습니다.
value
와 input
(change
) 사용하기
첫번째 방법은 value
속성과 input
혹은 change
등의 이벤트를 이용하는 방법입니다.
<input :value="message" @input="updateMessage">
// ...
computed: {
...mapState({
message: state => state.obj.message
})
},
methods: {
updateMessage (e) {
this.$store.commit('updateMessage', e.target.value)
}
}
// ...
mutations: {
updateMessage (state, message) {
state.obj.message = message
}
}
setter와 getter 사용하기
두번째 방법은 computed
속성에 setter와 getter를 정의하는 방법입니다.
<input v-model="message">
// ...
computed: {
message: {
get () {
return this.$store.state.obj.message
},
set (value) {
this.$store.commit('updateMessage', value)
}
}
}
참고
'Vue.JS' 카테고리의 다른 글
[Vue.JS] Vue.JS 소스코드 분석 (2) | 2019.09.05 |
---|---|
[vuex] Testing (0) | 2019.07.19 |
[vuex] Plugins (0) | 2019.07.16 |
[vuex] Modules (0) | 2019.07.16 |
[vuex] Actions (2) | 2019.07.11 |
댓글
공지사항
최근에 올라온 글