LoginSignup
3
4

More than 3 years have passed since last update.

【ヘルパー関数】ストアとコンポーネント間の通信

Posted at

参考文献
Vue.js入門

Vueインスタンスにstoreを渡してあるものとします。

ヘルパー関数

ヘルパー関数とは、コンポーネントからストアにアクセスする為の関数で下記の4つが用意されています。

・mapState
・mapMutations
・mapGetters
・mapActions

これを使い、コンポーネントの算出プロパティやメソッドに結び付けられます。

比較のためにthis.storeを使った参照の例を書きます。

this.storeを使って参照

store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment: function(state) {
      state.count++
    }
  }
})
App.vue
<template>
  <div id="app">
    <p>{{ count }}</p>
    <button v-on:click="increment(1)">add1</button>
  </div>
</template>

<script>
export default {
  computed: {
    count: function() {
      //store内のcountのstateを渡す
      return this.$store.state.count
    }
  },
  methods: {
    increment: function(value) {
      //ストア内の'increment'mutationをcommit
      this.$store.commit('increment', value)
    }
  }
}
</script>

ヘルパー関数を使って参照

先ほどのApp.vueをmapStateとmapMutationsを使い記述した例です。

App.vue
<template>
  <div id="app">
    <p>{{ count }}</p>
    <button v-on:click="increment">add1</button>
  </div>
</template>

<script>
// 'mapState'と'mapMutations'を使えるようにする
import { mapState, mapMutations } from 'vuex'

export default {
  // '$sotre.state.count'をthis.countと結びつける
  computed: mapState([
    'count'
  ]),
  // 'this.$store.commit('increment', value)'を、this.increment(value)で呼び出せる
  methods: mapMutations([   
    'increment'
  ]),
}
</script>

また、 下記のようにヘルパー関数の引数にオブジェクトを渡すと、コンポーネント上でthis.プロパティ名で参照可能になります。

App.js
import { mapState } from 'vuex'

export default {
  // '$sotre.state.count'をthis.valueと結びつける
  computed: mapState({
    value: 'count'
  })
}

ヘルパー関数は簡単にコンポーネントからストアを使うことができますが、これでは通常の算出プロパティやメソッドを書く場所がなくなります。
そのような場合、ヘルパー関数の戻り値と通常のこれでは通常の算出プロパティ・メソッドの定義を、オブジェクトスプレッド演算子やobject.assign関数で結合し、両方一度に使うことができます。

下記はmapStateでstateのcountを結びながら通常の算出プロパティdoubleを定義しています。

App.vue

import { mapState } from 'vuex'

export default {
  // 通常の算出プロパティを定義
  computed: {
    double: function() {
      return this.conut * 2
    },
    // 通常の算出プロパティとmapStateの戻り値を結合
    ...mapState([
      'count'
    ])
  }
}

名前空間つきのモジュールは、ヘルパー関数の第一引数に名前空間の文字列を渡すことにより記述できます。
下記は、counter名前空間にあるcountをthis.countに結ぶ例です。

App.vue
import { mapState } from 'vuex'

export default {
  // '$store.state.counter.count'を'this.count'に結ぶ
  computed: mapState('counter',[
    'count'
  ])
}

以上です。
また学習が進み次第、更新、掲載していきます。
ここまでで補足や訂正などありましたらご教授いただけると嬉しいです。
最後まで読んでいただきありがとうございます。

3
4
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
3
4