LoginSignup
89
85

More than 3 years have passed since last update.

【Vuex】mapState, mapGetters, mapMutations, mapActionsの最低限の使い方まとめ

Last updated at Posted at 2020-01-08

はじめに

Vuexの以下ヘルパーについて、最低限の使い方をまとめました。

大きく分けて以下2つに分けて覚えればOKです。

1.状態を呼び出す

  • mapState
  • mapGetters

2.状態を変化させる

  • mapMutations
  • mapActions

※Vuexの導入方法stateとは?という基本については当記事では触れていません。

環境

OS: macOS Catalina 10.15.1
Vue: 2.6.10
vuex: 3.1.2

map○○を使うメリット

以下のようにシンプルに呼び出せることが最大のメリットです。

this.$store.state.state1 //通常
this.state1 //mapState使用

this.$store.getters.getter1 //通常
this.getter1 //mapGetters使用

this.$store.commit('mutation1', 引数) //通常
this.mutation1(引数) //mapMutations使用

this.$store.dispatch('action1', 引数) //通常
this.action1(引数) //mapActions使用

使い方

1.Vuexから使うヘルパーをインポート

まず、全てのヘルパーに共通の作業です。
以下のようにそのコンポーネント内で使うヘルパーをインポートします。

Anything.vue
<script>
  import { mapState } from 'vuex'
//...
</script>

複数使う場合は,区切りで書けばOKです。

Anything.vue
<script>
  import { mapGetters, mapMutations } from 'vuex'
//...
</script>

2.必要なstate, getters, mutations, actionsをリストアップ

このリストアップ方法は複数ありますが、そのバリエーションは公式ドキュメントや他記事をご参照下さい。

当記事では最も使われると思われる

  • スプレッド演算子を使用して書く
  • ストア内の名前テンプレート内で呼び出す名前が同じになる

というパターンのみ記載します。

※ここから書く場所が

  1. computed
  2. methods

の2通りに分かれるのでご注意下さい。

2-1.mapState, mapGettersの場合

computed内に書く

※mapGettersの場合を例にします。

Anything.vue
<script>
  import { mapGetters } from 'vuex'

  export default {
//...
  computed: {
    ...mapGetters([
      'getter1',
      'getter2'
    ]),
    //スプレッド演算子を使うと他のものと共存できる。
    otherComputed() {
      //...
    }
//...
  }
</script>

2-2.mapMutations, mapActionsの場合

methods内に書く

Anything.vue
<script>
  import { mapGetters } from 'vuex'

  export default {
//...
  methods: {
    ...mapActions([
      'action1',
      'action2'
    ]),
    //スプレッド演算子を使うと他のものと共存できる。
    otherMethod() {
      //...
    }
//...
  }
</script>

3.テンプレート内でリストアップしたものを使用する

3-1.mapState, mapGetters

以下のように呼び出せます。

冒頭で触れたとおり、非常にシンプルです

Anything.vue
this.getter1
this.getter2

3-2.mapMutations, mapActions

以下のように呼び出せます。

該当のactionに引数がある場合()内に引数を入れればOKです。

Anything.vue
this.action1(引数)
this.action2(引数)

おわりに

最後まで読んで頂きありがとうございました:bow_tone1:

どなたかの参考になれば幸いです:relaxed:

参考にさせて頂いたサイト(いつもありがとうございます)

89
85
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
89
85