再利用可能なモジュールとは
- Vuexのモジュールの一種。
- シングルトンじゃないモジュール。
- OOP的に類推すると、普通のモジュールはシングルトンオブジェクトで、再利用可能なモジュールはクラス。
再利用可能なモジュールが役立つシーン
- コピペコードの回避
- エラーの状態
- ロード中/ロード済みの状態
- これらは違う画面(モジュール)でも、storeの型が共通していることが多い。
再利用可能なモジュールの作り方
モジュールを再利用可能にするのは簡単で、state
属性をオブジェクトから関数に書き換えるだけ。
/**
* 再利用可能なカウンターモジュール
*/
const counter = {
namespaced: true,
// stateが下記のようなオブジェクトだと、再利用できなくなるので注意
//
// state: {
// count: 0
// },
state() {
return {
count: 0
};
},
actions: {
increase({ state, commit }) {
commit("setCounter", state.count + 1);
}
},
mutations: {
setCounter(state, newValue) {
state.count = newValue;
}
}
};
ストアに組み込むときは、modules
で宣言するが、キーをモジュール名にし値をモジュールにする。下記の例だと、再利用可能なカウンターモジュールを3つ作っている。それぞれ別の状態を持つ。
/**
* ストア
*/
const store = new Store({
modules: {
counter1: counter,
counter2: counter,
counter3: counter
}
});
状態やアクションをコンポーネントにバインドするにはいつもどおりmapState
とmapActions
でできる。
const app = {
name: "app",
computed: {
...mapState(["counter1", "counter2", "counter3"])
},
methods: {
...mapActions({
increase1: "counter1/increase",
increase2: "counter2/increase",
increase3: "counter3/increase"
})
},
template: `
<div>
<button @click="increase1">counter1 = {{ counter1.count }}</button>
<button @click="increase2">counter2 = {{ counter2.count }}</button>
<button @click="increase3">counter3 = {{ counter3.count }}</button>
</div>
`
};
ここで例示したコードはCodePenのvuex reusing modulesにて公開しているので実際に動作を確認できる。