【问题标题】:In Vuex, why are the module's state accessed as 'store.state.module' instead of 'store.module.state'?在 Vuex 中,为什么模块的状态被访问为 'store.state.module' 而不是 'store.module.state'?
【发布时间】:2021-12-20 10:41:14
【问题描述】:

在下面的代码中,为什么moduleA的状态是用store.state.a而不是store.a.state访问的?

由于store 拥有moduleA,而moduleA 拥有其state,所以如果moduleA 的state 使用store.a.state 访问,对我来说更有意义。

const moduleA = {
  state: () => ({ ... }),
  ...
}

const moduleB = {
  state: () => ({ ... }),
  ...
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> `moduleA`'s state
store.state.b // -> `moduleB`'s state

【问题讨论】:

    标签: vue.js vuex vuex-modules


    【解决方案1】:

    之所以是store.state.a而不是store.a.state是因为Vuex中只有一个状态对象。在底层,所有模块都组合成一个状态对象。

    Vuex docs 可以为您提供更多信息。

    【讨论】:

    • 文档的那一部分帮助这更有意义。我认为 vue 所做的所有抽象都会抽象出商店在后台的工作方式,并让我们使用store.a.state,因为我们在每个模块中声明了state。
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 2019-03-22
    • 2021-08-27
    • 2019-11-17
    • 2017-12-05
    • 2017-05-12
    • 2018-05-19
    • 2021-05-15
    相关资源
    最近更新 更多