代码之家  ›  专栏  ›  技术社区  ›  netik

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

  •  2
  • netik  · 技术社区  · 8 年前
    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
        },
    })
    

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

    从我的组件中,我访问 Users 存储方式如下:

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

    但我不明白为什么我要打电话 this.$store.state.Users this.$store.Users

    我是说,模块 用户 商店状态中没有定义对吗?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Community Mohan Dere    6 年前

    说明:

    this.store.state.Users.users

    • 第一个 Users 属性访问器表示模块的名称。
    • 第二个 users 属性表示的内部对象属性 用户 单元

    如果你想打电话 this.$store.state.Users 这百货商店状态用户。用户 要访问您的用户阵列,请定义 Users.js 以稍微不同的方式。

    请参阅代码:

    用户。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 是一个对象。它包含 mutations , getters ,方法如下 dispatch 还有更多。此对象的属性之一是 state 它本身所以如果你想直接从 $store 对象,显然您必须直接访问它: this.$store.state ...

    this.$store.Users.state 每个模块的属性。

    吸气剂 . 这是最佳实践。