import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
my_property: 47
},
getters: {
getMyProperty: state => {
return state.my_property;
}
},
mutations: {
setMyProperty: ( state, payload ) => {
state.my_property = payload;
}
},
actions: {
doChangeMyProperty: ( context, payload ) => {
context.commit('setMyProperty', payload);
},
doAsyncChangeMyProperty: ( { commit }, payload ) => {
// Using a timeout, but any async operation can go here
setTimeout(function () {
commit('setMyProperty', payload);
}, 1000);
}
}
});
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // moduleA's state
store.state.b // moduleB's state
<template>
<div>
<div>Value = {{ getMyProperty }}</div>
<div>Value = {{ getStoredProp }}</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters([
'getMyProperty'
]),
// or, without helper...
getStoredProp: () => {
return this.$store.getters.getMyProperty;
}
}
}
</script>
<template>
<div>
<button @click="setMyProperty(22)">Set to 22</button>
<button @click="setThatProp(0)">Reset to 0</button>
</div>
</template>
<script>
import { mapMutations } from 'vuex';
export default {
methods: {
...mapMutations([
'setMyProperty'
]),
// Or without helper...
setThatProp( value ) {
this.$store.commit( 'setMyProperty', value );
}
}
}
</script>
<template>
<div>
<button @click="doChangeMyProperty(5)">Change me to 5</button>
</div>
</template>
<script>
import {mapActions} from 'vuex';
export default {
methods: {
...mapActions([
'doAsyncChangeMyProperty',
]),
// Or without helper...
doThatThing( value ) {
this.$store.dispatch('doAsyncChangeMyProperty', value);
}
}
}
</script>
<template>
<div>
<input type="text" v-model="my_property"/>
{{ my_property }}
</div>
</template>
<script>
export default {
computed: {
my_property: {
get() {
return this.$state.getters.my_property;
},
set( value ) {
this.$state.dispatch('setMyProperty', value);
}
}
}
}
</script>
No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.