我个人对vuex的理解是state中定义的变量类似于java中的全局变量,将各个组件使用的变量统一收集和管理,而getter、mutation、action是query和updatefunctionstatefunctionsfortheseglobalvariables:存放全局变量的地方,可以是字符串,数据,对象等定义:exportdefaultnewVuex.Store({state:{count:0,price:0,metaInfo:{title:"Thisisatitle",keywords:"vuex,vue.js,vue-router",}}})getter函数:相当于计算属性定义:exportdefaultnewVuex.Store({state:{count:0,price:0,metaInfo:{title:"Thisisaheader",keywords:"vuex,vue.js,vue-router",}},getters:{getMoney:function(state){返回state.count*state.price},getMoney2:function(state){returnstate.count*state.price},}})参考:常规方法:this.$store.getters.getMoneymapGetters方法,有2个方法1、使用对象的方法引用,这里可以同时进行多个引用。..mapGetters({getMoneyFromState:'getMoney',getMoneyFromState2:'getMoney2'}),....this.getMoneyFromState//使用时这样调用2.使用name的方法引用...mapGetters(['getMoney','getMoney2'])//...this.getMoney//使用时调用1和2的效果是一样的。说白了,mapGetter只是提供了一种引用的方式,避免每次引用都写那么长的表达式mapActions和mapMutations都是这个思路的变异函数:用来定义状态中改变变量的方法。毕竟直接调用的方式也不太优雅。定义:Vue.use(Vuex);exportdefaultnewVuex.Store({state:{count:0,price:5.5,metaInfo:{title:"Thisisatitle",keywords:"vuex,vue.js,vue-router"}},mutations:{updatePrice(state,price){state.price=price;},updateCount(state,count){state.count=count}}})每个变异方法有两个参数,状态和输入参数,并且突变必须同步执行正常的调用方法:this.$store.commit("updatePrice",val);usemapMutationsmethod:exportdefault{methods:{...mapMutations(['updatePrice','updateCount']),//使用时直接按照方法inputPrice(price){this.更新价格(价格);}}}mutation是一个方法,所以这里需要集成到methods中动作功能:将mutation中处理数据的方法改成可以异步执行的方法,一个action中可以调用多个mutation方法定义:exportdefaultnewVuex.Store({state:{count:0,price:5.5,metaInfo:{title:"这是一个标题",keywords:"vuex,vue.js,vue-router"}},getters:{getMoney:function(state){returnstate.count*state.price},getMoney2:function(state){returnstate.count*state.price}},mutations:{updatePrice(state,price){state.price=price;},updateCount(state,count){state.count=count},actions:{updateOrderInfo(context,info){context.commit('updatePrice',info.price);context.commit('updateCount',info.count);}},modules:{}});引用:import{mapActions}from'vuex'methods:{...mapActions(['updateOrderInfo']),inputPrice(){this.updatePrice(this.price);这个.$store.state.price;},getMyMoney(){this.updateOrderInfo({price:this.price,count:this.count});},getMyMoney2(){this.$store.dispatch('updateOrderInfo',{price:this.price,count:this.count});}}常规方法,利用dispatchthis.$store.dispatch('updateOrderInfo',{price:this.price,count:this.count});mapActionmethod:this.updateOrderInfo({price:this.price,count:this.count});summarystate:用于定义全局变量getter:将state封装成一个计算属性,whichisconvenient获取全局变量mutation:定义状态中改变全局变量的方式。这些方法都是同步动作:定义异步方法state、getter、mutation和改变状态的action。可以通过常规的this.$store直接引用mapGetters和mapActions,mapMutations只是定义了另一种引用方式,避免每次都写长表达式,使用哪种方式看个人喜好!
