我想从 records_view.js
访问 instance.js
中的 state.session
。这是如何实现的?
存储/模块/instance.js
const state = {
// This is what I want to access in records_view.js
session: {}
};
const getters = {
sessionGetter: state => state.session
};
存储/模块/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
);
}
};
这是为了增加一点上下文。
存储/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
}
});
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 模块,但需要一个突变来更新不同文件中的状态。能够通过添加这个来实现这一点
即使在模块中,您也可以通过 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;
}
}
context.commit('user/change_amount', new_amount, {root: true})
就我而言,这就是它对我有用的方式。
在文件 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'
这样,状态参数可以在子模块中交叉引用。
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;
},
},
不定期副业成功案例分享