Front-End/Vue.js
[Vue.js] Vuex 사용법(state, getters, mutations, actions)
김당
2021. 7. 19. 15:56
이번엔 Vuex 구조들에 대해서 정리해보겠습니다.
1) state
: state는 Vue의 data로 볼 수 있습니다
: state는 직접 변경이 불가하고 mutations을 활용해야 변경할 수 있습니다. 여러 컴포넌트에서 state를 변경하는 경우 어느 컴포넌트에서 해당 state를 변경했는지 추적하기 어렵기 때문입니다.
#state 사용법
export const store = new Vuex.Store({
state:{
message: 'hi'
}
});
<h1>{{ this.$store.state.message }}</h1>
2) getters
: state값을 접근하는 속성이자, Vue의 computed처럼 미리 연산된 값을 접근하는 속성입니다.
#getters 사용법
export const store = new Vuex.Store({
state:{
num: 5
},
getters:{
getNumber(state){
return state.num;
}
}
});
<h1>{{ this.$store.state.message }}</h1>
3) mutations
: mutations는 state의 값을 변경할 수 있는 메서드입니다.
: mutations 내 메서드 정의 시에 첫 번째 인자로 state가 전달됩니다.
: mutations는 commit()으로 동작시킬 수 있습니다.
#mutations 사용법
export const store = new Vuex.Store({
state:{
num: 5
},
mutations:{
addNum(state){
state.num++;
}
}
});
<template>
<div>
<button v-on:click="addBtn">add num</button>
<h1>{{this.$store.state.num}}</h1>
</div>
</template>
<script>
export default {
methods:{
addBtn: function(){
this.$store.commit('addNum');
}
}
}
</script>
#mutations 사용법_인자값 넘기기
: 인자를 넘기고 싶을때에는 mutations명 뒤에 인자를 넣어주면 됩니다.: 인자를 두개 이상 넘기고 싶을 때에는 payload를 사용하여 객체를 넘겨줄 수 있습니다.1) 인자 1개 넘길 때
export const store = new Vuex.Store({
state:{
num: 5
},
mutations:{
addNum(state, index){
state.num = state.num + index;
}
}
});
template>
<div>
<button v-on:click="addBtn">add num</button>
<h1>{{this.$store.state.num}}</h1>
</div>
</template>
<script>
export default {
methods:{
addBtn: function(){
this.$store.commit('addNum',5);
}
}
}
</script>
2) 인자 2개 이상 넘길 때
export const store = new Vuex.Store({
state:{
num: 5
},
mutations:{
addNum(state, payload){
state.num = state.num + payload.index;
}
}
});
<template>
<div>
<button v-on:click="addBtn">add num</button>
<h1>{{this.$store.state.num}}</h1>
</div>
</template>
<script>
export default {
methods:{
addBtn: function(){
this.$store.commit('addNum',{index: 5, clicked: true});
}
}
}
</script>
4) actions
: actions는 비동기 작업을 담당하는 속성입니다.
# actions 사용법
export const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
setTimeout(() => context.commit('increment'), 2000);
}
}
});
<template>
<div>
<button v-on:click="startTimer">timer</button>
<h1>{{this.$store.state.count}}</h1> </div>
</template>
<script>
export default {
methods:{
startTimer: function(){
this.$store.dispatch('increment');
}
}
}
</script>