0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vuex:mapState,mapGetters,mapActions,mapMutationsの使い方

Posted at

「これ何に使うの?」と思ったら予想外に便利なので書く。

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...に書いてあげたほうがあとあとラクになります。

mapGettersmapActionsは特に沢山呼び出す時は使えると思います。
以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?