LoginSignup
2
4

More than 5 years have passed since last update.

Vuex 状態管理ライブラリ メモ

Last updated at Posted at 2019-03-28

state

state状態データを持てる
サイト全体の状態保存可能
ただやりすぎると可読性やらが落ちます

  state: {
    count: 0
  },

stateを表示させたい時(コンポーネント内で)

<p>{{$store.state.conut}}</p>

stateを表示させたい時(コンポーネント外で)

this.$store.state.conut

mutations

実際に Vuex のストアの状態を変更できる唯一の方法は、ミューテーションをコミットすることです。

とにかくmutations使わずにstateは変更できないので
変更したときはmutations使う

  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 状態を変更する
      state.count++
    }
  }

mutationsを使うにはcommitしなければならないです。
store.commit('increment')

これでおk
あとは
ミューテーションハンドラ関数は同期的でなければならないこと
何故かと言うとコールバックは、ミューテーションがコミットされた時点ではまだ呼び出されないから

actions

-アクションは、状態を変更するのではなく、ミューテーションをコミットします。
-アクションは任意の非同期処理を含むことができます。

要は非同期処理したかったらactionsで定義して
dispatchで動かせってことです。

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

アクションは store.dispatch がトリガーとなって実行されます:

store.dispatch('increment')

この一連の流れを理解するのにだいぶかかった...

非同期の操作したい場合例

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}
2
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
2
4