Home > Enterprise >  Vuex store is inaccessible
Vuex store is inaccessible

Time:03-12

I made a vuex store:

export const general = {
    namespaced: true,
    state: {
        menuEnabled: true,
        headerEnabled: true
    },
    getters: {
        menuState: state => state.menuEnabled,
        headerState: state => state.headerEnabled
    },
    actions: {
        setMenuVisibility({commit}, visibility) {
            commit('setMenuVisibility', visibility);
        },
        setHeaderVisibility({commit}, visibility) {
            commit('setHeaderVisibility', visibility);
        }
    },
    mutations: {
        setMenuVisibility(state, visibility){
            state.menuEnabled = visibility;
        },
        setHeaderVisibility(state, visibility){
            state.headerEnabled = visibility;
        }
    }
}

index.js

import { createStore } from "vuex";
import { auth } from "./auth.module";
import {general} from "./general.module";

const store = createStore({
    modules: {
        general,
        auth
    },
});
export default store;

main.js

import router from "./router";
import store from "./store";

createApp(App)
    .use(store)
    .use(router)
    .mount('#app')

After that, I created 2 computed functions in App.vue:

computed: {
    menuVisibilityState : function (){
      return this.$store.state.menuEnabled;
    },
    headersVisibilityState : function () {
      return this.$store.state.headerEnabled;
    }
  }

But, I can't get them from vuex:
enter image description here

I tried to import general directly in App.vue and get the values.
It doesn't work and I think, that it's bad way to get them.

Can somebody help me?

CodePudding user response:

When you create a module in Vuex, the local state is nested depending on the name you've provided to the module (this happens when you're accessing the root state.).

In your example, to access the local state of general module you could write:

computed: {
    menuVisibilityState : function (){
      return this.$store.state.general.menuEnabled;
    },
    headersVisibilityState : function () {
      return this.$store.state.general.headerEnabled;
    }
  }

Keep in mind that:

actions and mutations are still registered under the global namespace - this allows multiple modules to react to the same action/mutation type. Getters are also registered in the global namespace by default. https://vuex.vuejs.org/guide/modules.html#namespacing

  • Related