Ye' Thura Ag
Ye' Thura Ag

Reputation: 143

Vuex module state undefined in global mutations

Is there a way to access module state from global mutations file? In Vuex documentation, I only found How to access global assets from namespaced modules

Below is my vuex structure.

In users/state.js,

const state = {
  selected_users: [],
}
export default state;

Then imported Users module's state, getters, mutations, actions in index.js like below:

import * as actions from './actions.js';
import * as mutations from './mutations.js';
import * as getters from './getters.js'
import state from './state.js'

export default {
  namespaced: false,
  actions,
  mutations,
  getters,
  state,
}

In main store file:

import Vue from "vue";
import Vuex from "vuex";
import { state } from "./state";
import * as getters from "./getters";
import * as actions from "./actions";
import * as mutations from "./mutations";
import users from './modules/users';

const modules = {
  users
}

Vue.use(Vuex);

const store = new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
  modules,
});

export default store;

Then from global mutations file, when accessing the module state selected_users, it's undefined.

export const UPDATE_LIST = (state, list) => {
  // do something with list
  
  // then wants to use selected_users
  console.log(state.selected_users);
}

Upvotes: 0

Views: 261

Answers (1)

Robert S
Robert S

Reputation: 836

You can access the global store as below.

First import the main store file global in main.js

Write the below code in your user/state.js file.

const state = {
  selected_users: [],
}
const getters = {
  selected_users(state) {
    return state.selected_users;
  },
} 
export default state;

When accessing the module state you can use the below code.

console.log(state.getters.selected_users);

Upvotes: 0

Related Questions