「これ何に使うの?」と思ったら予想外に便利なので書く。
store.js
例えばこんなstoreがあるとします。
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
hoge:'',
},
getters:{
hogetters: (state) => state.hoge,
},
mutations:{
updateHoge(state,payload){
const self = this
self.state.hoge = payload
},
},
actions:{
getHoge(value){
const self = this
self.dispatch('updateHoge',value)
}
},
});
Sample.vue
Componentsの最初に読み込んでおきます。
<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
name: 'HogeVue',
computed:{
...mapState({
hoge:'hoge',
})
...mapGetters({
hogetters:'hogetters',
}),
},
methods:{
...mapActions({
getHoge:'getHoge',
}),
...mapMutations({
updateHoge:'updateHoge',
}),
},
}
</script>
すると、こんな風にラクに書けます。
<template lang="pug">
.sample
h1 {{hogetters}}
p(@click="getHoge('fuga')") {{hoge}}
</template>
<script>
//(上記map...は省略します)
methods:{
sample(){
const self = this
self.updateHoge('fuga')
},
},
</script>
storeの値を呼び出す時に
this.$store.state.hoge
this.$store.getters.hogetters
と毎回書いていくと、数が多くなるにつれてダルくなってきますので、
使うものは最初にmap...に書いてあげたほうがあとあとラクになります。
mapGettersとmapActionsは特に沢山呼び出す時は使えると思います。
以上です。