Search code examples
javascriptvue.jsvuexvuex-modules

How to access 'this' in Vuex store module state


For example, say I have a "store" directory like this:

...
store
├── auth
│   └── user.js
└── index.js
...

index.js

import Vue from 'vue';
import Vuex from 'vuex';
import {user} from './auth/user';

Vue.use(Vuex);

/* eslint-disable no-new */
const store = new Vuex.Store({
  modules: {
    user
  },
});

export default store;

Now in the user store I have some constants and other state variables in it's state prop. How can I access state props from within itself? For example user store may look like this:

user.js

export const user = {
  namespaced: true,

  state: {

    // hardcoded string assigned to user.state.constants.SOME_CONST
    constants: {
      SOME_CONST: 'testString'
    },

    // Another property where I would like to reference the constant above

    someOtherStateProp: {

      // Trying to access the constant in any of these ways throws
      // 'Uncaught ReferenceError: .... undefined'
      // Where '...' above is interchangeable with any root I try to access the constant from (this, state etc)

      test1: this.state.constants.SOME_CONST,
      test2: user.state.constants.SOME_CONST
      test3: state.constants.SOME_CONST
      test4: constants.SOME_CONST
      test5: SOME_CONST
      // .... etc. All the above throw ReferenceError's 
    }
  }
};

How can I reference user.state.constants.SOME_CONST from user.state.someOtherStateProp.test1?

Feel like I'm missing something very fundamental here.


Solution

  • The simplest way would be declarimg the CONSTANTS object before exporting your module amd acceessing them as below

    const CONSTANTS = {
        SOME_CONST: 'testString'
    }
    
    export const user = {
      namespaced: true,
    
      state: {
    
        // hardcoded string assigned to user.state.constants.SOME_CONST
        constants: CONSTANTS,
    
        // Another property where I would like to reference the constant above
    
        someOtherStateProp: {
    
    
          test1: CONSTANTS.SOME_CONST,
        }
      }
    };