LoginSignup
2
1

More than 3 years have passed since last update.

Vuexの勉強記録

Last updated at Posted at 2019-08-06

Vuexについて初めて勉強したため、その勉強記録。

Vuexのインストール

公式ガイドより引用

npm

npm install vuex --save

yarn

yarn add vuex

コアコンセプト

ストアを作成する。

src/store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    message: 'hogehoge'
  },
})
export default store

stateはコンポーネントでいうdata

src/main.js
import store from '@/store.js'

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

これで全てのコンポーネントから使用可能

コンポーネント
export default {
    this.$store.state.message
}

getters

stateを取得するための算出データ

src/store.js
const store = new Vuex.Store({
  state: {
    list: [
      { id: 1, name: 'Taro', age: 10 },
      { id: 2, name: 'Jiro', age: 12 },
      { id: 3, name: 'Emi', age: 15 }
    ]
  },
  getters: {
    person: state => {
      return id => state.list.find(el => el.id === id)
    }
  }
})
export default store
コンポーネント
export default {
    console.log(this.$store.getters.person(2));
};
// listからidが2の要素を返す

mutations

stateの値を変更するメソッド。コンポーネントでいうmethods
mutations内の関数はストアのcommitで発火させることができる。
Vuexの状態(state)を第1引数として持ち、payload(コミットからの引数)を第2引数として持つことができる。

commit

登録されているmutationsを呼び出す。コンポーネントでいう$emit的な存在。
ミューテーションを起動するためには、ミューテーションのタイプを指定し、store.commitで呼び出す必要がある。
commitも追加の引数(payload)を持つことができる。payloadにはオブジェクトを持たせることができる。

actions

非同期処理を含めることができ、ミューテーションをコミットする。

src/store.js

const store = new Vuex.Store({ 

  state: {
    counter: 0
  },
  getters: {
    counter(state) {
      return state.counter
    }
  },
  mutations: {
    countUp(state, payload) {
      state.counter += payload.amount
    }
  },
  actions: {
    countUp({ commit }) {
      commit('countUp', { amount: 10 })
    }
  }
})
export default store

コンポーネントからアクションを呼び出すときはdispatchを用いる

コンポーネント
methods: {
    countUp() {
      this.$store.dispatch("countUp");
    }
  }

アクションの第1引数は次のようなオブジェクトになっており、上記の{ commit }のように分割代入を使えば、任意のプロパティを受け取ることができる。

{
  state,  // store.stateと同じ
  rootState, //store.stateと同じ(モジュール内に限る)
  commit,  // store.commitと同じ
  dispatch,  // store.dispatchと同じ
  getters,  // store.gettersと同じ
  rootGetters //store.gettersと同じ(モジュール内に限る)
}

ここまでを図で表すと
image.png

マッピングヘルパー

ゲッターやミューテーションを複数使用するとき、全てを記述すると冗長になるため、ヘルパーが用意されている。先ほど記載したコードは下記のようにコンポーネントから呼び出すことができる。

コンポーネント
import { mapGetters, mapActions } from "vuex";

export default {
  computed: mapGetters(["counter"]),
  // counter() {
  //   return this.$store.getters.counter;
  // } と同じ

  methods: mapActions(["countUp"])
  // countUp() {
  //   this.$store.dispatch("countUp");
  // }  と同じ
  }

 参考文献

公式ガイド
基礎から学ぶVue.js

2
1
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
2
1