[Vuejs]-Simplify Vuex modules access

3👍

Have you looked into the map* helpers? They allow you to import state, getters, mutations and actions directly onto your component as regular properties.

import { mapGetters, mapActions } from 'vuex'

export default {
  computed: {
    ...mapState('moduleB', [
      'someGetter'
    ])
  },

  methods: {
    ...mapActions('moduleA', [
      'save'
    ]),

    test() {
      // Same as this.$store.dispatch('moduleA/save')
      this.save()

      // Same as this.$store.getters['moduleB/someGetter']
      this.someGetter
    }
  }
}

Other than that, the syntax you propose isn’t possible, but there’s nothing stopping you from writing your own helper functions to ease its usage.

If you really want your proposed syntax, you can hack it like this (untested):

function createModuleProxy(store, module) {
  return {
    state: new Proxy({}, {
      get(target, prop) {
        return store.state[module][prop]
      },
      set(target, prop, value) {
        store.state[module][prop] = value
        return true
      },
    }),
    getters: new Proxy({}, {
      get(target, prop) {
        return store.getters[module + '/' + prop]
      },
    }),
    dispatch(mutation, payload) {
      return store.dispatch(module + '/' + mutation, payload)
    },
    commit(action, payload) {
      return store.commit(module + '/' + action, payload)
    }
  }
}

store.moduleA = createModuleProxy(store, 'moduleA')
store.moduleB = createModuleProxy(store, 'moduleB')

store.moduleA.dispatch('save')
store.moduleB.getters['someGetter']

Leave a comment