最近,我第一次在 Vuex 中实现模块时遇到了困难。我找不到关于我收到的控制台错误消息的太多信息(rawModule is undefined
),所以我想我应该分享我遇到的问题和解决方案。当我处理一些示例时,我正在做一个快速、简单的模块实现版本:
export const store = new Vuex.Store({
state: {
loggedIn: false,
user: {},
destination: ''
},
mutations: {
login: state => state.loggedIn = true,
logout: state => state.loggedIn = false,
updateUser: ( state, user ) => { state.user = user },
updateDestination: ( state, newPath ) => { state.destination = newPath }
},
modules: {
project
},
});
const project = {
state: {}
}
Run Code Online (Sandbox Code Playgroud)
最终的问题是,我在尝试将模块添加到 Vuex 商店后声明了它。我原以为由于变量提升,稍后声明模块就可以了,但事实似乎并非如此。这是有效的代码:
const project = {
state: {}
}
export const store = new Vuex.Store({
state: {
loggedIn: false,
user: {},
destination: ''
},
mutations: {
login: state => state.loggedIn = true,
logout: state => state.loggedIn = false,
updateUser: ( state, user ) => { state.user = user },
updateDestination: ( state, newPath ) => { state.destination = newPath }
},
modules: {
project
},
});
Run Code Online (Sandbox Code Playgroud)
希望这可以节省一些人的时间。我在文档中没有看到任何需要特定顺序的内容,所以我很惊讶它的重要性。如果有人对它为什么这样工作有一些见解,我真的很想听听!也许是因为该Vuex.Store()
函数在设置值之前被调用project
,所以项目模块的值被封装为undefined
,这会导致错误?
归档时间: |
|
查看次数: |
2187 次 |
最近记录: |