如何在模块 vuex js store 中设置全局突变
How to set global mutation in module vuex js store
我需要能够从任何 Vuex 模块更改全局变量 alert
的状态。
store/index.js:
export const state = () => ({
alert: null
})
store/child.js:
export const mutations = {
SET_ALERT: function (rootState, alert) {
rootState.alert = alert
}
}
export const actions = {
setalert({commit}){
commit('SET_ALERT', 'warning')
}
}
我想调用 setalert
并将全局 store.state.alert
设置为 "warning"
。目前,store.state.child.alert
被设置为 "warning"
。
您无法从另一个模块的变更中访问 vuex 模块的状态。
现在您的 SET_ALERT
突变正在引用 child
状态,因为它在 child
模块的范围内。将状态对象的参数名称更改为 rootState
不会更改它的内容。
但是,您可以简单地将 SET_ALERT
突变移动到 index.js
文件中。仍然可以从 child
模块的 setalert
操作中调用突变。
如果您正在为模块 (namespace: true
) 使用命名空间,则需要在 commit
调用中明确说明要使用根模块,如下所示:
commit('SET_ALERT', 'warning', { root: true });
我需要能够从任何 Vuex 模块更改全局变量 alert
的状态。
store/index.js:
export const state = () => ({
alert: null
})
store/child.js:
export const mutations = {
SET_ALERT: function (rootState, alert) {
rootState.alert = alert
}
}
export const actions = {
setalert({commit}){
commit('SET_ALERT', 'warning')
}
}
我想调用 setalert
并将全局 store.state.alert
设置为 "warning"
。目前,store.state.child.alert
被设置为 "warning"
。
您无法从另一个模块的变更中访问 vuex 模块的状态。
现在您的 SET_ALERT
突变正在引用 child
状态,因为它在 child
模块的范围内。将状态对象的参数名称更改为 rootState
不会更改它的内容。
但是,您可以简单地将 SET_ALERT
突变移动到 index.js
文件中。仍然可以从 child
模块的 setalert
操作中调用突变。
如果您正在为模块 (namespace: true
) 使用命名空间,则需要在 commit
调用中明确说明要使用根模块,如下所示:
commit('SET_ALERT', 'warning', { root: true });