1 2 3 4 5 6 7 8 9 10 11 12 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); export const store = new Vuex.Store({ state: { counter: 0 }, });
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 computed: { parentCounter() { return this .$store.state.counter; } }, computed: { childCounter() { return this .$store.state.counter; } }, <!-- App.vue --> <div id="app" > Parent counter : {{ parentCounter }} <!-- ... --> </div> <!-- Child.vue --> <div> Child counter : {{ childCounter }} <!-- ... --> </ div>
getters 사용
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 export const store = new Vuex.Store({ state: { counter: 0 }, getters: { doubleCounter: function (state ) { return state.counter * 2 ; } } }); computed: { doubleCounter() { return this .$store.getters.doubleCounter; } }, computed: { doubleCounter() { return this .$store.getters.doubleCounter; } },
mapGetters
1 2 3 4 5 6 7 import { mapGetters } from 'vuex' computed: mapGetters({ parentCounter : 'getCounter' }),
주의 mapGetters를 쓰면 다른 computed 속성과 사용 불가, ES6 문법 …을 사용해야 함.
https://babeljs.io/docs/plugins/preset-stage-2/
1 2 3 4 5 6 7 8 9 10 11 import { mapGetters } from 'vuex' computed: { ...mapGetters([ 'getCounter' ]), anotherCounter() { } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 export const store = new Vuex.Store({ mutations: { addCounter: function (state, payload ) { return state.counter++; } } }); <!-- App.vue --> <div id="app" > Parent counter : {{ parentCounter }} <br> <button @click="addCounter" >+</button > <!-- ... --> </div> / / App.vue
인자 넘길라면
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 mutations: { addCounter: function (state, payload ) { state.counter = payload.value; } } methods: { addCounter() { this .$store.commit('addCounter' , 10 ); this .$store.commit('addCounter' , { value: 10 , arr: ["a" , "b" , "c" ] }); } },
1 2 3 4 5 6 7 8 9 10 11 12 13 import { mapMutations } from 'vuex' methods: { ...mapMutations([ 'addCounter' ]), ...mapMutations({ addCounter: 'addCounter' }) }
actions : 비동기 처리시, mutations는 동기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 export const store = new Vuex.Store({ mutations: { addCounter: function (state, payload ) { return state.counter++; } }, actions: { addCounter: function (context ) { return context.commit('addCounter' ); }, getServerData: function (context ) { return axios.get("sample.json" ).then(function ( ) { }); }, delayFewMinutes: function (context ) { return setTimeout(function ( ) { commit('addCounter' ); }, 1000 ); }, asyncIncrement: function (context, payload ) { return setTimeout(function ( ) { context.commit('increment' , payload.by); }, payload.duration); } } });
1 2 3 4 5 6 7 8 9 10 11 import {mapActions} from 'vuex' ;export default { methods: { ...mapActions([ 'asyncIncrement' , 'asyncDecrement' ]) }, }
Reference
Comment and share