Vuex:从另一个模块访问状态

Vuex: Access State From Another Module

我想从 records_view.js 访问 instance.js 中的 state.session。这是如何实现的?

store/modules/instance.js

const state = {
  // This is what I want to access in records_view.js
  session: {}
};

const getters = {
  sessionGetter: state => state.session
};

store/modules/records_view.js

const actions = {
  getSettingsAction (context, props) {
    // This is how I'm trying to access session, which doesn't work
    let session = context.state.instance.session;

    Api(
      context,
      {
        noun: props.noun,
        verb: 'GetRecordsViewSettings',
        orgUnitKey: _.has(session, 'orgunit.key') ? session.orgunit.key : '',
        data: {}
      },
      props.callback
    );
  }
};

这是为了增加一点上下文。

store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';
import * as getters from './getters';
import * as types from './mutation-types';

import instance from './modules/instance';
import recordsView from './modules/records_view';

Vue.use(Vuex);

export default new Vuex.Store({
  state,
  actions,
  getters,
  mutations,
  modules: {
    instance,
    recordsView
  }
});

您需要像下面这样在您的状态中定义 session,以便在您的 getters:

中访问它
const state = {
  session: ''
}

您必须编写一个 mutation,它将从您的操作中调用以设置此状态值。

state引用本地状态,访问其他模块的状态时应使用rootState

let session = context.rootState.instance.session;

文档:https://vuex.vuejs.org/en/modules.html

来自一个动作:

'contacts:update' ({ commit, rootState }) {
    console.log('rootState', rootState.users.form)
    ......

  },

对我来说,我有 vuex 模块,但需要一个突变来更新不同文件中的 STATE。能够通过添加 THIS

来完成此操作

即使在模块中,您也可以通过 console.log(this.state)

查看您可以访问的全局状态
const mutations = {
MuteChangeAmt(state, payload) {
//From user module; Need THIS keyword to access global state
this.state.user.payees.amount = payload.changedAmt;
 }
}

就我而言,这就是它对我有用的方式。

在文件 ModuleA.js 中:

export const state = {
    parameterInA: 'A'
 }
export const action = {
    showParameterB() {
    console.log("Parameter B is: " + this.state.B.parameterInB)
}

在文件模块 B 中:

export const state = {
    parameterInB: 'B'
 }

export const action = {
    showParameterA() {
    console.log("Parameter A is: " + this.state.A.parameterInA)
}  

您需要在 index.js 中为根目录导入 ModuleA 和 B:

import * as A from 'ModuleA.js'  
import * as B from 'ModuleB.js'

这样就可以在子模块中交叉引用state参数了

this.$store.state.instance.session

其中“instance”是模块名称,“session”是您尝试访问的 Vuex 状态变量。

假设您有两个模块:ModuleA & ModuleB.

如果您想从 ModuleB 访问 ModuleA 的 状态,您可以执行以下操作:

// inside ModuleB (where there is stateA in ModuleA)
getters: {
        getStateA(state, _, rootState) {
            return rootState.ModuleA.stateA;
        },
    },