Search code examples
vue.jsvuexvuex-modules

Vuex rootActions with several modules


I have a vuejs on client side, where I use vuex for state management. I have several modules (in separate files) but some of the modules, has very similar actions, that's why I want to create dry code.

My goal: Creating a root action, what can be called by every modules.

My main vuex looks like this:

export default new Vuex.Store({
  actions: {
    rootactions,
  },
  modules: {
    users,
    classes,
    studentgroups,
    // ... other stuff
  }
})

How should I refer the rootactions methods?

Thanks for the responses in advance!


Solution

  • How about to create a separate file RootActions.js with the common actions

    export default {
        action1: () => {
            //
        },
        action2: () => {
            //
        },
    }
    

    And then import it in your module file e.g. User.js

    import RootActions from './RootActions'
    
    const state = {
        // state object
    }
    
    const mutations = {
        // mutations object
    }
    
    const actions = {
        // actions object
    }
    
    export default {
      namespaced: true,
      state,
      mutations,
      actions: Object.assign(RootActions, actions)
    }