Search code examples
vue.jsvuex

How to call a shared helper function from within a mutation or action in Vuex


I am trying to separate out some code that is common among many calls in my Vuex mutations. I am getting the feeling that this is discouraged but I don't understand why.

Have a look at an image of some sample code below:

I have added this 'helpers' entry in the Vuex - this obviously doesn't exist but how can I call the shared helper function 'getColumn' from mutations and/or actions?

enter image description here


Or do I have resort to calling a static method on a 'VuexHelper' class? :(

Something like:

enter image description here

Note I have already looked at the following:

  1. Vue Mixins - yes, something like that could work but is not supported in Vuex - also, vue methods don't return a value...
  2. I have looked at Modules but these still don't give me what I need, i.e. a simple re-usable function that returns a value.

Thanks


Solution

  • I don't see why you may want to put the helper function within the store. You can just use a plain function.

    function getColumn(state, colName) {
      // Do your thing.
    }
    
    const vstore = new Vuex.Store({
      // ....
      mutations: {
        removeColumn(state, colName) {
          var column = getColumns(state, colName);
        }
      }
    };
    

    On the other hand, if you really need that, you can access the raw module and all that's included:

    var column = this._modules.root._rawModule.helpers.getColumns(state, colName);
    

    Although this syntax is not documented and can change for later versions.