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
}
现在这个州是平的。因此不需要额外的数据访问器。
第二个更好的选择
使用吸气器。
请参阅第二个选项的代码:
const state = {
users: []
}
const getters = {
getUsers(state) {
return state.users
}
}
export default {
state,
getters
}
现在你可以写:$this.store.getters['getUsers']
使用namespaced:true
可能需要付出更多的努力。研究它。
编辑1
CCD_ 14是一个对象。它包含mutations
、getters
、dispatch
等方法。该对象的属性之一是state
本身。因此,如果您想直接从$store
对象访问状态,显然必须直接访问它:this.$store.state ...
this.$store.Users.state
这并没有发生。vuex引擎不会为每个模块添加另一个CCD_ 22属性。
选择第二个更好的选择——getter。这是最好的做法。