G. Marc
G. Marc

Reputation: 5997

How to use non-namespaced and namespaces modules at the same time in Vuex

I'm trying to have a state that consists of namespaced modules and a global state. Unfortunately, I can access the global actions but I can't get the global state properties.

If I try to use mapState in a component like this,

computed: {
  ...mapState(['editMode']),
  ...mapState('address', ['addresses']),
}

I have access to addresses, but editMode is always undefined. Mapping actions works flawlessly and updates the state according to the Vuex Chrome Tool.

But I noticed, that the global state is shown under its own "namespace" "global". So I tried to map using ...mapState('global', ['editMode']), but got an error that the namespace does not exist.

Here's my code:

index.ts

import Vue from 'vue';
import Vuex from 'vuex';
import address from './modules/address';
import global from './global';

Vue.use(Vuex);

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

modules/address.ts

export default {
  namespaced: true,

  state: {
    addresses: [],
  },

  mutations: {
    ...
  },

  actions: {
    ...
  },
};

global.ts

export default {
  namespaced: false,

  state: {
    editMode: 0,
  },

  mutations: {
    SET_EDIT_MODE(state, value) {
      state.editMode = value;
    },
  },

  actions: {
    setEditMode({ commit }, editMode) {
      commit('SET_EDIT_MODE', editMode);
    },
  },
};

Upvotes: 0

Views: 442

Answers (1)

Radu Diță
Radu Diță

Reputation: 14171

State is not affected by namespace. In a way it always gets namespaced. This is so we don't have collision.

To access a state from a module you need to get a bit verbose:

computed: {
 ...mapState({
   editMode: state => state.global.editMode
 }),
 ...mapState('address', ['addresses']),
}

Upvotes: 1

Related Questions