问题描述
我最近开始使用 vuex
.
官方docs
很好地解释了模块是,但我不确定我是否理解模块中的命名空间.
The official docs
explains well what modules are but i am not sure if i understood the namespaces in modules right.
有人能以更好的方式介绍命名空间吗?何时/为什么使用它?
Can anybody put some light on namespaces in a better way? When/why to use it?
非常感谢.
推荐答案
当你有一个包含非常大的 state 对象的大应用时,你通常会把它分成 模块.
When you have a big app with a very large state object, you will often divide it into modules.
这基本上意味着您将状态分解为更小的部分.一个警告是你不能对一个模块使用相同的方法名称,因为它被集成到相同的状态,例如:
Which basically means you break the state into smaller pieces. One of the caveats is that you can't use the same method name for a module since it is integrated into the same state, so for example:
moduleA {
actions:{
save(){}
}
}
moduleB {
actions:{
//this will throw an error that you have the same action defined twice
save(){}
}
}
因此,为了启用此功能,您可以选择将模块定义为命名空间,然后您可以在不同的模块中使用相同的方法:
So in order to enable this you have the option to define the module as namespaced, and then you can use the same method in different modules:
moduleA {
actions:{
save(){}
},
namespaced: true
}
moduleB {
actions:{
save(){}
},
namespaced: true
}
然后你这样称呼它:
this.$store.dispatch('moduleA/save')
this.$store.dispatch('moduleB/save')
请注意,如果您使用 mapGetter
或 mapActions
可能会使事情变得有点复杂,因为 getter 现在采用 ['moduleA/客户']
Please note that it might complicate things a bit if you're using mapGetter
or mapActions
since the getters are now in the form of ['moduleA/client']
所以只有在您确实需要时才使用它.
So use it only if you really need to.
这篇关于vuex 中模块的命名空间究竟是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!