Search code examples
vue.jsvuexnuxt.jsvuex-modules

How to use mapGetters with Vuex Modules


i have added modules in store/index.js

import NavMessage from './nav/message/index';
new Vuex.Store({
  modules: {
    NavMessage,
  },
});

my message/index.js

import state from './state';
import getters from './getters';
import mutations from './mutations';

export default {
  state,
  getters,
  mutations,
};

here is getters

const getters = () => ({
  getCount: state => {
    return state.count;
  },
});

export default getters;

i am trying to get data from NavMessage/getCount

...mapGetters({
    count: 'NavMessage/getCount',
  }),

but i am getting error unknown getter: NavMessage/getCount

help me thank


Solution

  • Below is a working example.

    I've made two important changes:

    1. I've added namespaced: true to the module.
    2. I've removed the wrapper function from around the getters.

    If you don't want to use namespacing then you'll need to change the mapGetters argument to count: 'getCount' instead. The NavMessage/ prefix is only required with namespacing.

    const mapGetters = Vuex.mapGetters
    
    const state = {
      count: 6
    }
    
    const getters = {
      getCount: state => {
        return state.count
      }
    }
    
    const mutations = {}
    
    const NavMessage = {
      namespaced: true,
      state,
      getters,
      mutations
    }
    
    const store = new Vuex.Store({
      modules: {
        NavMessage
      }
    })
    
    const app = new Vue({
      store,
    
      computed: {
        ...mapGetters({
          count: 'NavMessage/getCount',
        })
      }
    })
    
    console.log(app.count)
    <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>

    You've tagged the question with Nuxt. If you are using Nuxt I strongly suggest reading their guide to using the store:

    https://nuxtjs.org/guide/vuex-store

    Nuxt does things a little differently but as far as I'm aware you still shouldn't have a function wrapper around your getters. The namespaced: true will be added automatically and you shouldn't need to create the new Vuex.Store yourself. Nuxt creates the store itself and adds modules based on the folder structure.