4gi*_*ivN 3 vue.js vuex rootstate
我试图了解rootStatevuejs、vuex 是什么……但找不到这些关键词的明确解释(谷歌或其他论坛):
谁能解释一下它是什么,以及我们如何利用它的用法?
为了更好地构建代码,您可以将 vuex 存储拆分为不同的模块。请参阅参考资料。
这是我目前正在从事的项目中的商店示例:
在我的项目中,我需要来自 API 的多个数据,因此我决定在此 API 响应之后拆分我的商店,以将所有属于一个模块的功能捆绑在一起。本index.js是用来把所有的模块togehter和导出店:
...
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
})
Run Code Online (Sandbox Code Playgroud)
rootState如果我需要访问模块中的一般内容index.js或者我想从另一个模块内部访问模块中的数据,这将变得很重要。
例如:
要进行预订,我需要知道从我的应用程序的当前用户中选择了哪个类别。为了实现这一点,我只需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
}
}
Run Code Online (Sandbox Code Playgroud)
例如,您还可以传递rootGetters给一个动作。在我的示例中getter,我的类别模块中有一个从类别数组(= stateprop)返回当前选定类别的索引。
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']
}
Run Code Online (Sandbox Code Playgroud)
希望我的例子是可以理解的,我可以帮助你一点。