Вас*_*рин 4 javascript vuex vuejs2 nuxt.js
我需要能够alert从任何 Vuex 模块更改全局变量的状态。
商店/index.js:
export const state = () => ({
alert: null
})
Run Code Online (Sandbox Code Playgroud)
商店/child.js:
export const mutations = {
SET_ALERT: function (rootState, alert) {
rootState.alert = alert
}
}
export const actions = {
setalert({commit}){
commit('SET_ALERT', 'warning')
}
}
Run Code Online (Sandbox Code Playgroud)
我想调用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 });
Run Code Online (Sandbox Code Playgroud)