为了更好地构建您的代码,您可以将 vuex 存储拆分为不同的模块。请参阅reference。
这是我目前正在从事的项目中的商店示例:
在我的项目中,我需要来自 API 的多个数据,因此我决定在此 API 响应之后拆分我的存储,以将属于一个模块的所有功能捆绑在一起。 index.js 用于将所有模块放在一起并导出存储:
...
import categories from './modules/categories'
import transportation from './modules/transportation'
import insurances from './modules/insurances'
import booking from './modules/booking'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
categories,
transportation,
insurances,
booking
},
state: {
// here I have general stuff that doesn't need to be split in modules
},
mutations: {
// general stuff
},
actions: {
// general stuff
},
strict: true
})
如果我需要访问index.js 中的一般内容,或者如果我想从另一个模块内部访问模块中的数据,rootState 就变得很重要。
例如:
要进行预订,我需要知道从我的应用的当前用户中选择了哪个类别。为了实现这一点,我只需在操作中使用 rootState 道具:
/modules/categories.js
export default {
namespaced: true,
state: {
categories: [ // data I need acces to ]
}
/modules/booking.js
actions: {
async PUT_BOOKING({ state, commit, dispatch, rootState }) {
// access categories
const categories = rootState.categories.categories
// rootState -> access root
// categories -> namespaced module in store
// categories -> state categorie in namespaced module
}
}
例如,您也可以将rootGetters 传递给操作。在我的示例中,我的类别模块中有一个getter,它从类别数组(=state 道具)中返回当前选定类别的索引。
async PUT_BOOKING({ state, commit, dispatch, rootState, rootGetters }) {
// access categories
const categories = rootState.categories.categories
// acces index of selected categorie
const index = rootGetters['categories/selCategorie']
}
希望我的例子是可以理解的,我可以帮助你一点。