Marketingexpert
Marketingexpert

Reputation: 1461

Can't access Vuex getters outside of modules

I am unable to access the getters from one of my Vuex modules in my component, even though I can see the getter in Vue Dev Tools.

My store.js file:

import Vue from 'vue';
import Vuex from 'vuex';
import subsub from './modules/subsub';

Vue.use(Vuex);
export default new Vuex.Store({
  state: { },
  actions: { },
  mutations: { },
  getters: { },
  modules: {
    subsub,
  },
});

My modules/subsub.js file:

const state = {
  categories: [{
    name: 'one',
    path: 'two',
    ...
  }, {
    name: 'twocat',
    path: 'two',
    ...
  }],
};

const actions = { };
const mutations = { };
const getters = {
  filterCategories(state) {
    return state.categories;
  },
  filtertwo(state) {
    const filteri = state.categories.filter((catee) => {
      return catee.name === 'twocat';
    });
    return filteri;
  },
};

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters,
};

My component:

<template>
  <div> {{ filterCategories }} </div>
</template>

<script>    
import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters([
      'categories',
      'filtertwo',
      'filterCategories',
    ]),
    filtertwo() {
      return this.$store.getters.filtertwo;
    },
    filterCategories() {
      return this.$store.getters.filterCategories;
    },
  },

</script>

So, what I am missing? Is there any other syntax for accessing the getters from modules?

Upvotes: 5

Views: 5268

Answers (2)

thanksd
thanksd

Reputation: 55664

First, you don't have a getter for categories, so you need to add one.

Second, your subsub module has its namespaced property set to true. This means that you need to provide the module name to the mapGetter helper:

...mapGetters('subsub', [
  'categories',
  'filtertwo',
  'filterCategories',
]),

Third, the mapGetters function creates the filtertwo, and filterCategories computed properties for you. But, you are redefining them manually, returning the explicit reference to the $store.getters. However, you aren't referencing the namespace correctly, so they are returning undefined. Either get rid of these computed properties or reference the namespace correctly:

filtertwo() {
  return this.$store.getters['subsub/filtertwo'];
},
filterCategories() {
  return this.$store.getters['subsub/filterCategories'];
},

Upvotes: 7

Marketingexpert
Marketingexpert

Reputation: 1461

I found the solution, thnx to hints from @thanksd

By using the example above where namespaced is set true I had to add the following to the component

filterCategories() {
      return this.$store.getters['subsub/filterCategories'];
    },

Otherwise, if I didn't want to add the subsub, I could just set the namespaced to false. This issue took me a while to get my head around. Cheers

Upvotes: 0

Related Questions