LoginSignup
11
4

More than 3 years have passed since last update.

Vuex StoreのModule分割

Posted at

はじめに

Vuex便利ですよね!Vueでサービス作る上で欠かせない機能だと思います。
ただ規模が大きくなるにつれ肥大化が否めません。
そこでstoreをmoduleという単位で分割する方法、さらにそれらを別ファイル管理する方法を記載します。

module管理

まずmoduleで区切っていないストアの例を見てみましょう

src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userId: '',
    username: '',
    introduction: '',
    postArticles: [],
    notices: [],
    articles: [],
    articleId: '',
    popularArticles: [],
    searchAricles: [],
    followUsers: [],
    star: 0,
    help: [],
    topCarousel: [],
  },
  mutations: {
    saveUserInfo(state, userInfo) {
       ...
    },
    saveArticles(state, articles) {
       ...
    },
    saveStar(state, star) {
       ...
    },
    ...
  },
  actions: {
    loadUserInfo(context, authInfo) {
       ...
    },
    loadArticles(context) {
       ...
    },
    postArticles(context) {
       ...
    }
    ...
  },
  modules: {
  }
})

いかがでしょうか?
現状ユーザー情報, 記事情報, その他資材情報が入り乱れている状況です。
まだなんとなく追えますが、さらに機能追加された場合確実に訳が分からなくなります。

そこでModule区分です、上記ストアを機能事に分離できます。
分離することでどこになんの機能があるのか一発でわかるためコードのみやすさが格段に上がります。
また1ファイルあたりのコード量が増える懸念もあるので、Moduleごとにファイルを分けることもオススメです。

以下のような感じです

// ファイル構成
src/store/index.js // modulesの読み込み
src/store/modules //modulesの設置
src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import { user, article, material } from './modules';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    user,
    article,
    material,
  },
});
src/store/modules/index.js
import user from './user';
import article from './article';
import material from './material';

export {
  user,
  article,
  material,
};
src/store/modules/user.js
export default {
  namespaced: true,
  state: {
    userId: '',
    username: '',
    introduction: '',
    followUsers: [],
    star: 0,
  },
  mutations: {
   ...
  },
  actions: {
   ...
  },
};
src/store/modules/article.js
export default {
  namespaced: true,
  state: {
    postArticles: [],
    articles: [],
    articleId: '',
    popularArticles: [],
    searchAricles: [],
  },
  mutations: {
   ...
  },
  actions: {
   ...
  },
};
src/store/modules/material.js
export default {
  namespaced: true,
  state: {
    help: [],
    topCarousel: [],
    notices: [],
  },
  mutations: {
   ...
  },
  actions: {
   ...
  },
};

このように区分することで今後のストアの増加にも対応できます。
現時点で必要なさそうでも導入は早めが楽です、是非導入のご検討いかがでしょうか?

11
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
11
4