Search code examples
vue.jsvuexvuex-modules

VUEX - Many mapActions with same action name on the same page


I have several differents files for a lot of modules. Some of the share the same action name

There is some page that use 2 or more mapActions for different modules On my page is something like this:

methods: {
    ...mapActions({
        documents: ['setDocumentImage'],
        documentAddress: ['setDocumentImage'],
        selfie: ['setDocumentImage']
    }),
}

All my modules have a action setDocumentImage But the problem is that i have to invoke them like: this.setDocumentImage(file)

Is there a way to create an alias for each one of these mapAction that my page can differentiate? Or how can I fix it?


Solution

  • You can use namespacing if you are using modules in composing your store.

    Something like this:

     const moduleA = {
      namespaced: true, //namespacing set to true.
      state: { ... },
      mutations: { ... },
      actions: { ... },
      getters: { ... }
    }
    
    const moduleB = {
      state: { ... },
      mutations: { ... },
      actions: { ... }
    }
    
    const store = new Vuex.Store({
      modules: {
        namespacedModuleA: moduleA,
        b: moduleB
      }
    })
    

    Then in your mapAction you can do this :

    methods: {
        ...mapActions({
            actionOfA: ['nameSpacedModuleA/actionOfA'],
            actionOfB: ['actionOfB'],
        }),
    }
    

    If you do not want to use mapActions, you can also do

    this.$store.dispatch('nameSpacedModuleA/actionOfA')
    

    More on namespacing with modules here