2017-12-05 20 views
3

, 나는이 같은 "저장"디렉토리가 있다고 가정하십시오 지금액세스하는 방법 '이'Vuex 저장 모듈 상태에서 예를 들어

... 
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; 

user 가게 나는 상수와 다른 상태 변수가 state 소품에 있습니다. 자체 내에서 state 소품에 액세스하려면 어떻게해야합니까? 예를 들어 user 점은 다음과 같이 보일 수 있습니다 :

의 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 
    } 
    } 
}; 

어떻게 user.state.someOtherStateProp.test1에서 user.state.constants.SOME_CONST를 참조 할 수 있습니다?

나는 매우 근본적인 뭔가를 놓치고있는 것처럼 느껴진다.

+0

당신을합니까 아래로 당신의 모듈을 수출 AMD acceessing 전에 CONSTANTS 객체를 declarimg 것입니다 내에서 이러한 상수에 액세스하려면 -

let user = { namespaced: true, state: { SOME_CONST: 'testString' } }; Object.assign(user, { state: { someOtherStateProp: { test1: user.state.SOME_CONST } } }); export default user; 

여기 Object.assign에 대해 자세히 알아보기 모든 구성 요소는 @VamsiKrishna 예, 현재는 문제가되지 않습니다. –

+0

구성 요소의 '계산 된'소품에서 상태를 매핑 한 후 구성 요소에서 올바르게 액세스 할 수 있습니다. – DjH

답변

2

가장 간단한 방법은

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, 
    } 
    } 
};