Vuex mutations와 commit() 형식..

준영·2023년 10월 30일
0
post-thumbnail

Vuex mutations와 commit() 형식

mutations란

  • state의 값을 변경 할 수 있는 유일한 방법이자 메소드
  • mutation은 commit()으로 동작시킨다.

예시

store.js

state: { num: 10 },
mutations: {
	printNumbers(state) {
    	return state.num;
    }
  	sumNumbers(state, anotherNum) {
    	return state.num + anotherNum;
    }
}

App.vue

this.$store.commit('printNumbers');
this.$store.commit('sumNumbers', 20);

예시2

  • state를 변경하기 위해 mustations를 동작시킬 때 인자payload 를 전달 할 수 있음
  • 위와 다른 점은 보내고 싶은 인자가 많을 때, 아래와 같이 객체화 시켜서 key value 형태로 넘겨주면 된다.
    store.js
state: { storeNum: 10 },
mutations: {
	modifyState(state, payload) {
      	console.log(payload.str);
    	return state.storeNum += payload.num;
    }
}

App.vue

this.$store.commit('modifyState', {
	str: 'passed from payload',
  	num: 20
});
profile
개인 이력, 포폴 관리 및 기술 블로그 사이트 👉 https://aimzero-web.vercel.app/

0개의 댓글