使用 $store 对象访问 Vuex 子模块的内部状态

Accessing Vuex submodules inner state with the $store object

import Vue from 'vue'
import Vuex from 'vuex'
import Users from './modules/Users'

Vue.use(Vuex)

export const store = new Vuex.Store({
    namespaced: true,
    state: {
        foo: false,
    },
    modules: {
        Users
    },
})

和一个Users.js:

// initial state
const state = {
    users: [],
}
export default {
    state
}

从我的组件中,我正在像这样访问 Users 商店:

this.$store.state.Users.users.forEach((el) => {}

但我不明白为什么我必须调用 this.$store.state.Users 而不是 this.$store.Users

我的意思是,模块 Users 还没有在商店的状态下定义,对吗?

解释:

this.store.state.Users.users

  • 第一个 Users 属性 访问器表示您的模块的名称。
  • 第二个users属性表示的是属性的内部Object Users 模块的状态

如果您想调用 this.$store.state.Users 而不是 this.store.state.Users.users 来访问您的用户数组,请以稍微不同的方式定义 Users.js

见代码:

Users.js

// initial state
const state = []
export default {
    state
}

现在状态是平的。所以不需要额外的数据访问器。

第二个更好的选择

使用getters.

查看第二个选项的代码:

const state = {
  users: []
}
const getters = {
  getUsers(state) {
    return state.users
  }
}

export default {
 state,
 getters
}

现在你可以写:$this.store.getters['getUsers']

您的 namespaced:true 可能需要比这多一点努力。研究一下。

编辑 1

this.$store 是一个对象。它包含 mutationsgettersdispatch 等方法等等。该对象的属性之一是 state 本身。所以如果你想直接从 $store 对象访问状态,你显然必须直接访问它:this.$store.state ...

this.$store.Users.state 这不会发生。 vuex 引擎不会为每个模块添加另一个 state 属性。

选择第二个更好的选择 - getters。这是最佳做法。