How to use mapGetters with Vuex Modules

sid*_*art 4 vue.js vuex nuxt.js vuex-modules

i have added modules in store/index.js

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

my message/index.js

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

export default {
  state,
  getters,
  mutations,
};

Run Code Online (Sandbox Code Playgroud)

here is getters

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

export default getters;

Run Code Online (Sandbox Code Playgroud)

i am trying to get data from NavMessage/getCount

...mapGetters({
    count: 'NavMessage/getCount',
  }),
Run Code Online (Sandbox Code Playgroud)

but i am getting error unknown getter: NavMessage/getCount

help me thank

ski*_*tle 6

下面是一个工作示例。

我做了两个重要的改变:

  1. 我已经添加namespaced: true到模块中。
  2. 我已经从getters.

如果您不想使用命名空间,则需要将mapGetters参数count: 'getCount'改为。该NavMessage/前缀时,才需要用命名空间。

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)
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.1.2/dist/vuex.js"></script>
Run Code Online (Sandbox Code Playgroud)

你已经用 Nuxt 标记了这个问题。如果您使用 Nuxt,我强烈建议您阅读他们的商店使用指南:

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

Nuxt 做的事情有点不同,但据我所知你仍然不应该在你的getters. 在namespaced: true将被自动添加,你不应该需要创建new Vuex.Store自己。Nuxt 自己创建商店并根据文件夹结构添加模块。