P
P
postya2021-01-06 19:58:07
Vue.js
postya, 2021-01-06 19:58:07

How to properly use vuex modules?

Application on Vue
I want to separate the vuex logic into files, that is, modules.
I somehow apparently did it wrong, I get an error

"TypeError: Cannot read property 'state' of undefined"


How to properly use vuex modules?

Here's what I did:
There is an index.js in the store directory. It looks like this:
import Vuex from "vuex";
import Vue from "vue";
import snippets from "./modules/snippets";

Vue.use(Vuex);

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


In the store directory, I created the modules directory, and in this directory I created the snippets.js file, where the processing logic for one Vue component will be stored.

The snippets.js file looks like this:

const snippets = {
  namespaced: true,
  state: {
    filteredSnippets: ["apple", "banana"]
  },
  mutations: {
    SET_FILTERED_SNIPPETS: (state, snippets) => {
      state.filteredSnippets = snippets;
    }
  },

  actions: {
    FILTER_SNIPPETS({ commit }, snippets) {
      commit("SET_FILTERED_SNIPPETS", snippets);
    }
  }
};

export default snippets;


I get the state of the array in vuex like this in the vue component:
computed: { ,
    ...mapState("snippets", ["filteredSnippets"])
  },

mounted() {
    console.log(this.filteredSnippets);
  },


Project structure:

5ff5ebfa2365a231509240.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-01-06
@postya

and the store itself was added to the app?
I usually do this.
in app.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import StoreData from './store'
const store = new Vuex.Store(StoreData);
const app = new Vue({
    el: '#app',
      store,
});

in store/index.js
import bookings from './bookings'
import events from './events'

export default {
    modules: {
        bookings,
        events
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question