vuex中模块的命名空间究竟是什么

Abd*_*han 8 javascript vue.js vuex

我最近开始vuex.

官方docs解释了什么模块,但我不确定我是否理解模块中的命名空间.

任何人都能以更好的方式对命名空间有所了解吗?何时/为何使用它?

非常感激.

Tom*_*mer 17

如果你有一个包含非常大的状态对象的大应用程序,你通常会将它分成模块.

这基本上意味着你将状态分解成更小的部分.其中一个警告是,您不能对模块使用相同的方法名称,因为它已集成到同一状态,因此例如:

moduleA {
  actions:{
    save(){}
  }
}

moduleB {
  actions:{
    //this will throw an error that you have the same action defined twice
    save(){}
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,为了启用此功能,您可以选择将模块定义为命名空间,然后您可以在不同的模块中使用相同的方法:

moduleA {
  actions:{
    save(){}
  },
  namespaced: true
}

moduleB {
  actions:{  
    save(){}
  },
  namespaced: true
}
Run Code Online (Sandbox Code Playgroud)

然后你这样称呼它:

this.$store.dispatch('moduleA/save')
this.$store.dispatch('moduleB/save')
Run Code Online (Sandbox Code Playgroud)

请注意,如果您正在使用mapGettermapActions因为吸气剂现在采用的形式,它可能会使事情变得复杂['moduleA/client']

所以只有在你真的需要时才使用它.