1. Vuexとは
Vuexは、Vue.jsアプリケーションでグローバルな状態(データ)を管理するための仕組みです。これにより、複数のコンポーネント間でのデータ共有が容易になります。
2. プロジェクトにVuexを導入する手順
- Vuexパッケージのインストール
npm install vuex --save
- main.jsでVuexを読み込む
import Vuex from 'vuex';
Vue.use(Vuex);
- storeオブジェクトの作成
const store = new Vuex.Store({
state: { counter: 0 }
});
- Vueインスタンスにstoreを設定
new Vue({
el: '#app',
render: h => h(App),
router,
store // 共有データをVueインスタンスに接続
});
3. Vuexの主要な概念
- State: データを格納する場所。
- Mutation: 同期的にstateを更新する。
- Action: 非同期操作を処理する。
- Getter: 状態に基づいて新しい派生データを作成する。
以下はVuexストアの基本的な構造です。
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
getters: {}
});
4. Stateの使用方法
すべての共有データはStoreのstate内に格納されます。
const store = new Vuex.Store({
state: { counter: 0 }
});
コンポーネントからStateへのアクセス
- 直接アクセス:
this.$store.state.counter;
- mapStateを使用して計算プロパティとしてマッピング:
import { mapState } from 'vuex';
export default {
computed: {
...mapState(['counter'])
}
};
5. Mutationの使用方法
Store内のデータを変更するには、必ずmutationを使用します。
Mutationの定義
const store = new Vuex.Store({
state: { counter: 0 },
mutations: {
increment(state) {
state.counter++;
},
incrementBy(state, amount) {
state.counter += amount;
}
}
});
Mutationの呼び出し
- commitメソッドを使用:
this.$store.commit('increment');
this.$store.commit('incrementBy', 5);
- mapMutationsを使用:
import { mapMutations } from 'vuex';
export default {
methods: {
...mapMutations(['increment', 'incrementBy']),
increase() {
this.incrementBy(3);
}
}
};
6. Actionの使用方法
非同期操作はAction内で行います。最終的にはMutationを通じてstateを更新します。
Actionの定義
const store = new Vuex.Store({
mutations: {
increment(state) {
state.counter++;
}
},
actions: {
asyncIncrement({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
}
}
});
Actionの呼び出し
- dispatchメソッドを使用:
this.$store.dispatch('asyncIncrement');
- mapActionsを使用:
import { mapActions } from 'vuex';
export default {
methods: {
...mapActions(['asyncIncrement']),
triggerAsync() {
this.asyncIncrement();
}
}
};
7. Getterの使用方法
GetterはStore内のデータを加工し、新しい派生データを作成します。
Getterの定義
const store = new Vuex.Store({
state: { counter: 0 },
getters: {
doubleCounter: state => state.counter * 2
}
});
Getterの使用
- 直接アクセス:
this.$store.getters.doubleCounter;
- mapGettersを使用:
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters(['doubleCounter'])
}
};
まとめ
- Vuexの利点
- 共有データを集中管理できるため、開発と保守が容易。
- コンポーネント間のデータ共有が効率的に行える。
- Vuex内のデータはリアクティブであり、ページとの同期が保たれる。
- アクセス方法
this.$store.stateやthis.$store.commitなどによる直接的な操作。mapState,mapMutations,mapActions,mapGettersを使用した簡略化された操作。
- 注意点
- コンポーネント内で直接stateを変更しないこと。
- stateの変更はmutationsのみで行う。
- actionsでは非同期処理を行い、最終的にmutationsを通じてstateを更新すること。