2

I try to implement vuex modules and understand usage. While trying to import modules in my home.vue, I have found this solution:

import { FETCH_INDEX_ARTICLES } from "@/store/types/actions.type.js";
// imports this => export const FETCH_INDEX_ARTICLES = "fetchIndexArticles"
import { mapGetters, mapActions} from 'vuex'
export default {
  name: "Home",
  data() {
      return {}
  },
  computed: {
      ...mapGetters(['articles']),
    },
  methods: {
      ...mapActions([FETCH_INDEX_ARTICLES])
  }
  created() {
      this.$store.dispatch(FETCH_INDEX_ARTICLES);
  }
};

but instead I get

vuex.esm.js?2f62:438 [vuex] unknown action type: fetchIndexArticles
vuex.esm.js?2f62:950 [vuex] unknown getter: articles

store/index.js

export default new Vuex.Store({
  modules: {
    articles,
  }
});

store/modules/articles.js

const state = {
  articles: [],

};
const getters = {
  articles(state) {
    return state.articles;
  },
};
const mutations = {
  [SET_ARTICLES] (state, pArticles) {
    state.article = pArticles
    state.errors = {}
  }
}
const actions = {
  [FETCH_INDEX_ARTICLES] (context) {
    context.commit(FETCH_START)
    return ApiService
      .get('/articlelist/index/')
      .then((data) => {
        context.commit(SET_ARTICLES, data.articles);
        context.commit(FETCH_END)
      })
      .catch((response) => {
        context.commit(SET_ERROR, response.data.errors);
      })
    }
};
export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

How can I correctly import vuex module?

Thanks

ytsejam
  • 3,291
  • 7
  • 39
  • 69

1 Answers1

3

You must specify your modules, Your way is valid when you import your modules directly into your component

...mapGetters('articles', {
    article: 'articles',
})

this.article(2)

https://vuex.vuejs.org/guide/modules.html#binding-helpers-with-namespace

To facilitate the use I use the method dispatch for actions

this.$store.dispatch('articles/FETCH_INDEX_ARTICLES', {anydata})

Alexis Gatuingt
  • 490
  • 6
  • 20