Mutation은 state를 store로 옮기는 장점을 가지고 있다. 내부 component에서 직접 state를 추가해서 쓰지 말고, main.js에서 state를 정의해서 mutation으로 state를 작동시켜라!!
main.js에서 이용할 수 있다.
import { createApp } from 'vue';
import { createStore } from 'vuex';
import App from './App.vue';
const store = createStore({
state() {
return {
counter: 0
};
},
mutations: {
increment(state) {
state.counter += 2;
},
}
});
const app = createApp(App);
app.use(store);
app.mount('#app');
this.$store.commit()
메소드를 이용한다.commit
은 Vuex의 빌트인 메소드이고 string값으로 내가 수행하고자 하는 mutation의 이름을 취한다.한줄정리) main.js에서 mutations 속성을 통해 내가 정의한 state로 다양한 연산을 수행할 수 있고, mutation을 사용하려면 this.$store.commit() 메소드 안에 해당 mutation의 이름을 string값으로 넣어주면 된다.
일부 mutation은 arguments(parameter)를 필요로 할 수 있다.
increment mutation을 만들었을때 이건 하드코딩되어있다. → state.counter += 2;
그래서 우리는 **payload**
라는 두번째 argument를 사용할 수 있다.
main.js
mutations: {
increment(state) {
state.counter += 2;
},
increase(state, payload) {
state.counter = state.counter + payload.value;
}
}
App.vue(script의 methods 부분만)
methods: {
addOne() {
this.$store.commit('increase', { value: 10 }); //commit 표현법1
this.$store.commit({ //commit 표현방법 2
type:'increase',
value:10
});
},
},
앞서 main.js의 increase mutation의 argument로 state
와 payload
두 가지를 줬다.
value라고 쓴 건 내가 payload.value라고 이름붙였기 때문! 이름 붙이기 나름이다. (val 이라고 해도됨)
App.vue 전체 코드
<template>
<base-container title="Vuex">
<the-counter></the-counter>
<button @click="addOne">Add 10</button>
<change-counter></change-counter>
</base-container>
</template>
<script>
import BaseContainer from './components/BaseContainer.vue';
import TheCounter from './components/TheCounter.vue';
import ChangeCounter from './components/ChangeCounter.vue';
export default {
components: {
BaseContainer,
TheCounter,
ChangeCounter,
},
computed: {
counter() {
return this.$store.state.counter;
},
},
methods: {
addOne() {
this.$store.commit('increase', { val: 10 }); //commit 표현법1
this.$store.commit({ //commit 표현방법 2
type:'increase',
value:10
});
},
},
};
</script>
<style>
* {
box-sizing: border-box;
}
html {
font-family: sans-serif;
}
body {
margin: 0;
}
</style>
<template>
<button @click="addOne">Add 2</button>
</template>
<script>
export default {
methods: {
addOne() {
this.$store.commit('increment');
},
},
};
</script>
<style>
</style>
import { createApp } from 'vue';
import { createStore } from 'vuex';
import App from './App.vue';
const store = createStore({
state() {
return {
counter: 0
};
},
mutations: {
increment(state) {
state.counter += 2;
},
increase(state, payload) {
state.counter = state.counter + payload.val;
}
}
});
const app = createApp(App);
app.use(store);
app.mount('#app');