4

例如,假设我有一个这样的“商店”目录:

...
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商店可能看起来像这样:

用户.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

感觉好像我在这里遗漏了一些非常基本的东西。

4

2 回答 2

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

于 2017-12-05T12:11:38.007 回答
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,
    }
  }
}; 
于 2017-12-05T12:48:05.033 回答