はじめよう

At the center of every Vuex application is the store. A "store" is basically a container that holds your application state. There are two things that make a Vuex store different from a plain global object:

Vuex アプリケーションの中心にあるのは Store です。store の基本的な役割は、アプリケーションの state を保持するコンテナーです。Vuex の store と単なるグローバルなオブジェクトの違いには、次の二つがあります。

  1. Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes.

  2. You cannot directly mutate the store's state. The only way to change a store's state is by explicitly committing mutations. This ensures every state change leaves a track-able record, and enables tooling that helps us better understand our applications.

  1. Vuex の store は reactive である。Vue コンポーネントが Vuex の store から state を読み出している場合、store の state が変更されれば、それに反応する形で効率的にその値も更新されます。

  2. store の状態を直接変更してはいけません。変更する唯一の方法は、mutation に commit することです。これによって、全ての state に対する変更は、追跡可能な記録として残されます。またそのためにアプリケーションの状態を把握するための便利なツールを使用することができるようになります。

一番シンプルな store

Vuex をインストールしたら、次に Store を作りましょう。とくに難しいことはありません。単に state の初期値のための Object を与え、それから mutation も与えておきましょう。

// Make sure to call Vue.use(Vuex) first if using a module system
// module システムで vuex を使う場合には、まず Vue.use(Vuex) をするのを忘れないでください。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

さあこれで store.state という形で state オブジェクトにアクセスできるようになりました。また store.commit というメソッドで、state の変更をトリガーすることもできるようになりました。

store.commit('increment')

console.log(store.state.count) // -> 1

繰り返しになりますが、store.state.count にダイレクトにアクセスして変更するのではなく、mutation に commit している理由は、明示的に変更を追跡できるようにするためです。このシンプルな慣習によって、意図がより明確に現れ、コードを読み返す際にも App の state の変更が行われていることが明確に読み取れるようになります。加えて、このおかげで、全ての変更のログをとるツールを使うこともできます。スナップショットをとったり、さらに time travel debuggin をも可能にします。

store の state をコンポーネント内で使用するには、シンプルに computed プロパティの中で state を return してあげるだけです。なぜならば store の state は reactive だからです。state の変更をトリガーするためには、シンプルにコンポーネントの method で store に commit するだけです。

次の章では、より詳細にコアとなるコンセプトについてみていきましょう。まずは state から始めます。

Last updated