Search code examples
javascriptecmascript-6vue.jsvuex

Vuex createNamespacedHelpers is not working


I'm building a Vuex store with multiple modules. I want to easily define and map the types of the getters and the actions so that I can have automatic module name in the path instead calling $store.getters["modulename/gettername"] for all the methods.

I found that I can use createNamespacedHelpers helper from vuex library but it's not working or something is missing in my configuration.

Here is the namespace-helper.js file I have

import { createNamespacedHelpers } from 'vuex';
import { getters, actions } from './types';

const { mapGetters, mapActions } = createNamespacedHelpers('modulename');

export default {
  computed: mapGetters([
    getters.getMethod1,
    getters.getMethod2
  ]),
  methods: mapActions([
    actions.actionMethod1,
    actions.actionMethod2
  ])
}

In my vue.js I have

import Vue from 'vue';
import Vuex from 'vuex';
import store from './store/index';
import someModuleNameSpaceHelper from './store/modules/someModule/namespace-helper';

Vue.use(Vuex);

window.vueRoot = new Vue({
  el: '#vue-root',
  store,
  someModuleNameSpaceHelper ,
  computed: {

  }
});

I thought at this point I would have access to vuex getters like: vueRoot.getMethod1

Am I missing something?


Solution

  • You're using an object property value shorthand, so your code snippet

    window.vueRoot = new Vue({
      el: '#vue-root',
      store,
      someModuleNameSpaceHelper ,
      computed: {
    
      }
    });
    

    is equivalent to

    window.vueRoot = new Vue({
      el: '#vue-root',
      store,
      someModuleNameSpaceHelper: someModuleNameSpaceHelper,
      computed: {
    
      }
    });
    

    which is like doing

    window.vueRoot = new Vue({
      el: '#vue-root',
      store,
      someModuleNameSpaceHelper: {
        computed: {...}, // vue won't see this
        methods: {...}   // vue won't see this
      } ,
      computed: {
    
      }
    });
    

    How about changing it to

    window.vueRoot = new Vue({
      el: '#vue-root',
      store,
      computed: someModuleNameSpaceHelper.computed,
      methods: someModuleNameSpaceHelper.methods
    });