front-end/Vue.js
Vuex 기초배우기 #5 (mutations)
정구
2022. 2. 22. 10:23
728x90
state 값을 변환시킬 때는 mutation (동기)
컴포넌트 내에서도 state의 값을 변화시킬 수 있는데 왜 mutation이 필요할까?
여러 개의 컴포넌트에서 같은 state 값을 동시에 제어하게 되면, state 값이 어느 컴포넌트에서 호출되어 변경되었는지 추적이 어렵게 된다.
setter와 비슷한 역할이라고 생각하면 된다.
src/store.js
mutations: {
addUsers: (state, payload) => {
state.allUsers.push(payload);
},
},
state의 값을 변경하기 때문에 state를 인자로 받아온다.
payload에는 변경하기 위한 내용을 인자로 받아온다.
src/components/Users/SignUp.vue
<script>
export default {
data() {
return {
userId: null,
password: null,
name: null,
address: null,
src: null,
};
},
methods: {
signUp() {
let userObj = {
userId: this.userId,
password: this.password,
name: this.name,
address: this.address,
src: this.src,
};
this.$store.commit("addUsers", userObj);
this.clearForm();
},
clearForm() {
(this.userId = null),
(this.password = null),
(this.name = null),
(this.address = null),
(this.src = null);
},
},
};
</script>
EventBus의 역할을 mutation이 대신하게 된다.
mutation을 사용하기 위해서는 store에 commit으로 요청을 하게 되고
'addUsers'f라는 이름을 가진 mutation에 userObj를 인자로 넘긴다
userObj는 payload로 넘겨받는다.
728x90