javascript - Vuex store模块状态下如何访问 'this'

标签 javascript vue.js vuex vuex-modules

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

...
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 Prop ?例如 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

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

最佳答案

最简单的方法是在导出模块之前声明CONSTANT 对象并按如下方式访问它们

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

关于javascript - Vuex store模块状态下如何访问 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47652862/

相关文章:

javascript - 将字符串格式更改为剑道网格中的日期

javascript - 使用 vuex 从其他组件更改 v-model 的值

javascript - 如何使用 Supabase 中的 signUp() 方法在注册时添加其他用户信息

javascript - VUE JS无法自动运行时间倒计时

vue.js - 如何使用 websocket 突变组织 vuex

javascript - 如何使用 Angular 根据当前选择的语言更改导入 scss

javascript - 在 jQuery 完成修改表单中的值之前提交表单

javascript - Bootstrap 弹出窗口未显示在所有元素之上

javascript - Vue 中模态关闭后的操作

javascript - Vue 3 - 如何重命名通过 toRefs() 公开的保留关键字?