【问题标题】:How to access 'this' in Vuex store module state如何在 Vuex 商店模块状态中访问“this”
【发布时间】:2018-05-19 01:40:04
【问题描述】:

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

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

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

【问题讨论】:

  • 你想在任何组件中访问这些常量
  • @VamsiKrishna,是的,目前这不是问题。在组件computed props 中映射状态后,我可以在组件中正常访问它们

标签: javascript vue.js vuex vuex-modules


【解决方案1】:

最简单的方法是在导出模块之前声明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,
    }
  }
}; 

【讨论】:

    【解决方案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

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 2020-08-25
      • 2017-07-06
      • 1970-01-01
      相关资源
      最近更新 更多