管理全局变量,方便组件间的值传递1.创建文件1.在store文件夹新建index.js文件importVuefrom'vue'//introducevueimportVuexfrom'vuex'//introducevue//使用vuexVue。use(Vuex)//创建一个Vuex实例conststore=newVuex.Store({state:{count:1//保存的数据}})exportdefaultstore//导出store2,引用main.js中的文件,并导入实例storeobjectimportstorefrom./store/indexnewVue({store})2.State数据保存在index.js文件中,可以使用this.$store.state获取自定义数据3.Getters相当于computedinvue对于计算属性,getter的返回值会根据其依赖关系缓存起来,只有当其依赖关系的值发生变化时才会重新计算。getters可以用来监听和改变state中的值,并返回计算出的结果this.$store.getters.getStoreCount//在页面上这样写,可以直接调用getters中的方法//方法在index.js文件的getter中定义conststore=newVuex.Store({state:{count:1},getters:{getStoreCount:function(state){returnstate.count+1;}}})四、Mutations用于修改store中的值//在页面的方法中调用mutation方法methos:{addFun(){this.$store.commit("add");},reductionFun(){this.$store.commit("reduction");}}在index添加mutationsconststore=newVuex.Store({s到.js文件tate:{count:1},getters:{getStoreCount:function(state){返回state.count+1;}},mutations:{add(state){//注意写法state.count=state.count+1;},减少(状态){state.count=state.count-1;}}})五、Action上面的方法虽然可以修改页面的值,但是官方不推荐这样做,我们可以使用action调用mutation来改变stateconststore=newVuex.Store({state:{count:1},getters:{getStoreCount:function(state){returnstate.count+1;}},mutations:{add(state){//注意写法state.count=state.count+1;},reduction(state){state.count=state.count-1;}},actions:{//注册动作,类似vue中的方法addFun(context){//接收一个context对象,方法一样属性为store实例context.commit("add");},reductionFun(context){context.commit("reduction");}}})页面调用如下:methos:{addFun(){this.$store.dispatch("addFun");//this.$store.commit("添加");},reductionFun(){this.$store.dispatch("reductionFun");//this.$store.commit("reduction");}}如果要传递参数,可以在调用方法中依次添加。在文件//页面中,可以直接使用自定义变量名{{conuNum}}来表示import{mapState,mapActions,mapGetters}from'vuex'computed:{...mapState({countNum:state=>state.count})}//Mapthis.commonActionGet()tothis.$store.dispatch('commonActionGet')//这个方法名必须对应...mapActions(['commonActionGet','commonActionGetJSON'])...mapActions({'commonActionGet':'commonActionGet','commonActionGetJSON':'commonActionGetJSON'})7.总结1.index.js定义了Vuex.Store2.State相当于一个数据库,定义了数据的结构和初值3.getters获取state4.Actions提交状态调用mutations方法操作数据5.Mutations定义状态数据的修改操作6.mapState,mapGetters,mapActions,mapMutations用于映射
