LoginSignup
11
6

More than 5 years have passed since last update.

Vuexでモジュールと処理を細分化する

Posted at

Nuxt.jsを最近やり始めたんだけれど、Vuexでの状態管理がサクサクと書けて非常に良いな、という印象を持っている
んで、Vuexで利用する store フォルダ内のファイルをどのように分割するか、というと、これはどうやら人それぞれらしい

  • index.js 内に全てまかなう方法
  • index.jsposts.jsuser.js とみたいにモジュール毎にファイル分け
  • index.jsmutations.jsactions.jsgetters.jsのように状態管理の要素別にファイル分け

このような方法があるけれど、以下のようにモジュール別にフォルダを分けて、状態管理の要素別にファイル分けするという方法でやってみた

└── store
    ├── index.js
    └── posts
    │   ├── actions.js
    │   ├── getters.js
    │   ├── index.js
    │   └── mutations.js
    └── users
        ├── actions.js
        ├── getters.js
        ├── index.js
        └── mutations.js

このようにした理由はいくつかあるのだけれど、以下の2つが大きな理由

  • 複数人で開発するときの開発しやすさ
  • VuexでTypeScriptの導入がやりやすくなった時に、少しずつJavaScriptからTypeScriptへ移行できるようにする

store/index.jsで各モジュールをimportする

store/index.js
import Vuex from 'vuex'
import postsModule from './posts'
import usersModule from './users'

new Vuex.Store({
  modules: {
    posts: postsModule,
    users: usersModule,
  }
})

各モジュールのindex.jsに処理をimportする

actions、getters,mutationsをindex.jsでimportしておく
また、今回は各stateについてはモジュール内のindex.jsで定義した
namespaced: true にしておくことによって、他モジュールやcomponentからは モジュール名/postDatasモジュール名/アクション名 といったかんじで呼び出すことができる

store/posts/index.js
import actions from './actions'
import getters from './getters'
import mutations from './mutations'

export const state = () => ({
  postDatas: {},

  postComments: [],
})

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}

各々の処理を定義

以下のようにやっていく(例ではaction)

store/posts/actions.js
export default {
  async fetchPostBy({ commit }, { id }) {
    ....
  },
...

}

このケースだと、 posts/fetchPostBy でこのアクションを呼び出すことができる。
ただし、同じpostsモジュール内の場合だと fetchPostBy で呼び出すことが可能

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