Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 881
Marketingexpert Avatar asked May 03 '17 17:05

Marketingexpert


1 Answers

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'];
},
like image 193
thanksd Avatar answered Oct 18 '22 06:10

thanksd