例如,假设我有一个"商店"像这样的目录:
...
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.constants.SOME_CONST
引用user.state.someOtherStateProp.test1
?
感觉我在这里错过了一些非常基本的东西。
答案 0 :(得分:2)
您可以分两步完成此操作。
let user = {
namespaced: true,
state: {
SOME_CONST: 'testString'
}
};
Object.assign(user, {
state: {
someOtherStateProp: {
test1: user.state.SOME_CONST
}
}
});
export default user;
在此处详细了解Object.assign
- https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
答案 1 :(得分:2)
最简单的方法是在导出模块之前声明CONSTANTS
对象并将其加入,如下所示
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,
}
}
};