Mutations

오민영·2022년 2월 16일
0

Vuex

목록 보기
4/5
post-thumbnail

Reference

Vuex 란?
What is Vuex?
Vuex 시작하기

mutations로 getters와 동일하게 state의 값을 변환 시킬 때 사용한다.

Getters와의 차이점
1. mutations는 전달인자를 받을 수 있다.
2. computed가 아닌 methods에 등록한다.

Actions와의 차이점

  • Mutations는 동기적 로직을 정의한다.
  • Actions는 비동기적 로직을 정의한다.(API, get, post)

mutations 동기적 로직을 수행하는 성격상, 정의한 로직들이 순차적으로 일어나야 각 컴포넌트의 반영 여부를 제대로 추적할 수 있다.

// store.js
export const store = new Vuex.Store({
  state: {
    count: 0;
  },
  getters: {
    getCounter(state){
      return state.count * 2;
    }
  },
  mutations: {
    addCounter(state, payload){
      return state.counter++;
    }
  }
})
<!-- counter.vue -->
<template>
  <div>
    {{ count }}
    <button @click="increaseCnt">+</button>
  </div>
</template>

<script>
  export defatult{
  	computed: {
  		count(){
  			return this.$store.state.count;
  		}
  	},
  	methods: {
  		increaseCount(){
  			this.$store.commit('addCounter');
  		}
  	}
  }
</script>

mutations 인자 전달

각 컴포넌트에서 vuex의 state를 조작하는데에 필요한 특정 값을 전달하고 싶은 경우, commit()에 두번째에 인자를 추가한다.

필수는 아니지만 보통 인자명을 payload라고 칭한다.

// store.js
// ...
state: {
  count: 0;
},
mutations: {
  increment (state, payload) {
    state.count += payload.value
  }
}

// counter.vue
this.$store.commit('addCounter', 10);
this.$store.commit('addCounter', {
  value: 10,
  arr: ["a", "b", "c"]
});

mapMutations

mapGetters와 마찬가지로 Vuex의 helper 함수인 mapMutations를 사용해서 코드 가독성을 높일 수 있다.

// App.vue
import { mapMutations } from 'vuex'

methods: {
  // Vuex 의 Mutations 메서드 명과 App.vue 메서드 명이 동일할 때 [] 사용
  ...mapMutations([
    'addCounter'
  ]),
  // Vuex 의 Mutations 메서드 명과 App.vue 메서드 명을 다르게 매칭할 때 {} 사용
  ...mapMutations({
    addCounter: 'addCounter' // 앞 addCounter 는 해당 컴포넌트의 메서드를, 뒤 addCounter 는 Vuex 의 Mutations 를 의미
  })
}
profile
이것저것 정리하는 공간

0개의 댓글