Skip to content

New module option subStore #381

Closed
Closed
@ktsn

Description

@ktsn

This proposal is come up from the discussion in #359.

Summary of proposal

Modules will have subStore option that expects a sub store name. If the option is specified, a sub store will be created under store.subStores.

The sub store has state, getters, dispatch and commit which are same interface as Vuex.Store but state will be the local state of corresponding module.

If prefix option (another proposal #380) is specified, sub store will prefix all getters, actions and mutations types implicitly. For example, if we set prefix: 'user/' on sub store module, subStore.dispatch('login') will be transformed to rootStore.dispatch('user/login').

Why is this worth adding?

Currently, we need to collect state, getters, actions and mutations from global namespace when we use them on components even though we separate the application state and logics to each module.

It would be good to provide the sub store because we can load all assets in a module at once and use them without prefix.

Examples

Module definition:

const userModule = {
  subStore: 'user',
  prefix: 'userModule/'

  // module assets
  state: { ... },
  getters: {
    isAdmin () { ... }
  },
  actions: {
    login () { ... }
  },
  mutations: {
    setName () { ... },
  }
}

Usage of sub store:

const store = new Vuex.Store({
  modules: {
    user: userModule
  }
})

const user = store.subStores.user
user.state.id // -> store.state.user.id
user.getters.isAdmin // -> store.getters['userModule/isAdmin']
user.dispatch('login') // -> store.dispatch('userModule/login')
user.commit('setName') // -> store.commit('userModule/setName')

Component binding:

computed: {
  // 2nd argument will be sub store name
  ...mapGetters({
    admin: 'isAdmin' // -> admin: 'userModule/isAdmin'
  }, 'user')
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions