vuex的使用三部曲

80 阅读1分钟

安装

npm i vuex@3

配置

在 src/store/index \

1.引入

uTools_1651376170746.png

2.配置

uTools_1651376217129.png

3.暴露

uTools_1651376199473.png

vuex模块化

当我们开发的项目比较大时,store中的数据就可能比较多,这时我们store中的数据就可能变得臃肿,为了解决这一问题,我们就需要将store模块化(module),即每个模块拥有自己的state、mutation、action、getter、甚至是嵌套子模块
注意 注意 注意 注意:被模块化的store须要开启命名空间

export default {
    namespaced: true,//开启命名空间
    state: {
    	sum:0,
    	number:0
    },
    mutations: {
    	ADD_NUM(state,value){
  			state.sum+=value
  		}
    },
    actions: {
    },
}

模块化下五个方法的使用

访问state数据

this.$store.state.moduleA.sum

...mapState('moduleA',['sum','number'])
...mapState('模块名',['方法名1','方法名2'])

Mutaion修改state数据

this.$store.commit('moduleA/ADD_NUM',10)

...mapMutaions('moduleA',['ADD_NUM']),

action

this.$store.dispatch('moduleB/addZhang',{name:'小明',age:18})
this.$store.dispatch(' 模块名/方法名a',传参数据)

...mapActions('moduleB',['addZhang']),//参数在调用时传递 addZhang({name:'小明',age:18})

getter

this.$store.getters['moduleB/firstName']

...mapGetters('moduleB',['firstName'])