LoginSignup
17
14

More than 5 years have passed since last update.

Vuexで再利用可能なモジュールの作り方

Posted at

再利用可能なモジュールとは

  • 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
  }
});

状態やアクションをコンポーネントにバインドするにはいつもどおりmapStatemapActionsでできる。

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にて公開しているので実際に動作を確認できる。

17
14
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
17
14