使用vuex状态管理的modules进行分模块管理
情景:对于一个使用vue.js框架的大型的项目,如果项目中有好几个不同的业务模块,在数据共享的时候往往会使用vuex状态管理,在vuex中如果不进行模块化管理,store对象可能就变得非常臃肿,不仅不利于维护,也可能导致不同业务系统之间共享数据导致失误。解决:独立维护一个公共仓库store,将一些各业务系统或项目共享的数据放到里面,然后根据业务系统单独维护一个store模块(module),每..
情景:对于一个使用vue.js框架的大型的项目,如果项目中有好几个不同的业务模块,在数据共享的时候往往会使用vuex状态管理,在vuex中如果不进行模块化管理,store对象可能就变得非常臃肿,不仅不利于维护,也可能导致不同业务系统之间共享数据导致失误。
解决:独立维护一个公共仓库store,将一些各业务系统或项目共享的数据放到里面,然后根据业务系统单独维护一个store模块(module),每个模块单独维护自己的state、action、mutation、getter,最后注入到vue中
实践(使用vuex模块化开发):
store目录结构
- store
- --moduleA
- --actions.js
- --getters.js
- --index.js
- --mutations.js
- actions.js
- getters.js
- index.js
- mutation-types.js
- mutations.js
在moduleA中的actions.js、getters.js、mutations.js文件中分别导出定义的方法
export default {
fn (xxx,xxx) {
xxx
}
}
在moduleA中的index.js中先导入actions.js、getters.js、mutations.js文件中定义的方法,然后定义moduleA需要的state,最后export default 出去
import getters from './getters.js'
import mutations from './mutations .js'
import actions from './actions .js'
const state = {
}
export default {
namespaced: true, //使用命名空间
state,
getters,
mutations,
actions
}
在store的indexs.js文件中安装vuex并Vue.use(Vuex),然后new一个store实例,如下:
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters.js'
import mutations from './mutations .js'
import actions from './actions .js'
import moduleA from './moduleA/index.js'
Vue.use(Vuex)
const state = {
}
export default new Vuex.Store({
state,
getters,
mutations,
actions,
modules: {
moduleA
}
})
最后将store挂载到vue实例上
import store from './store/index.js'
new Vue({
store,
data: {
},
xxx
})
使用:假设在xxx.vue组件中
可以使用createNamespacedHelpers创建基于某个命名空间辅助函数。它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数。
import {createNamespacedHelpers} from 'vuex'
const moduleA = createNamespacedHelpers('moduleA')
或解构语法 const {mapState, mapGetters, mapMutatios} = createNamespacedHelpers('moduleA')
然后使用辅助函数,如
computed: {
...moduleA.mapGetters([
'xxx'
])
}
采用解构方式:
computed: {
...mapGetters([
'xxx'
])
}
如需要使用全局仓库store
import {mapState, createNamespacedHelpers} from 'vuex'
然后使用辅助函数,如
computed: {
...mapState([
'xxx'
]),
...moduleA.mapGetters([
'xxx'
])
}
其它辅助函数使用方式类似,结束了。。。
更多推荐
所有评论(0)