我试图理解 rootState
与 vuejs、vuex ......但无法用这些关键词找到明确的解释(谷歌或其他论坛):
谁能解释它是什么,以及我们如何利用它的使用?
最佳答案
为了更好地构建代码,您可以将 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
})
rootState
如果我需要访问 index.js
中的一般内容,这很重要或者如果我想从另一个模块内部访问模块中的数据。例如。:
要进行预订,我需要知道从我的应用程序的当前用户中选择了哪个类别。为了实现这一点,我只需使用
rootState
Action 中的 Prop :/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
到一个 Action 。在我的示例中,我有一个 getter
在我的类别模块中,它从类别数组(= state
Prop )中返回当前选定类别的索引。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']
}
希望我的例子是可以理解的,我可以帮助你一点。
关于vue.js - vuejs中的rootState是什么,vuex上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60120850/