Vuex是一个专门为vue.js服务的状态管理库(我自己的理解是:为vue框架存储全局数据,可以在各种本地组件中使用)特点:响应性:状态变化在store中也可以在组件中高效更新和更改商店状态的唯一方法是通过突变提交提交。dispatch方法是异步函数的核心:state单状态树-对象:每个模块可以有自己的状态树对象//定义conststate={inthestorecount:0,name:""}mapState辅助函数:将store中的多个状态映射到本地组件中的计算属性),//名称不变...mapState({firstName:'name'}]),//创建别名}getter:状态计算属性对象。如果需要使用store中的多个状态进行计算,获取的值应用于多个组件,可以使用getters。getters可以说是store的计算属性。Defineconstgetters={inthestore//带有属性的方法DefinedoCount1:(state,getters)=>{return"hello"+state.name}//返回带参数的函数方法定义,doCount2:(state,getters)=>(id)=>{return"hello"+state.name+"youridisnumber"+id}}访问也略有不同属性访问:this.$store.getters.doCount1方法访问:this.$store.getters.doCount2(id)mapGetters辅助函数,将store中的getter映射到本地组件中的计算属性import{mapGetters}from'vuex'computed:{//使用对象扩展操作符将这个属性混入本地组件...mapGetters(['doCount1']),}mutations:事件注册对象-改变store状态,不能直接调用,需要调用constmutationsthroughcommit={UPDATE_COUNT(state,num){state.count=state.count+num},}mapMutations:将存储中的突变映射到本地组件中的计算属性的辅助函数import{mapMutations}from'vuex'methods:{//使用对象扩展操作符将此方法混入本地组件...mapMutations(['UPDATE_COUNT']),}****注意,因为mutations必须是同步函数,为了解决异步函数,引入action,因此,任何类型的功能都可以包含在动作中。使用commit在突变中调用函数。使用dispatch调用异步函数。见action****actionsconstactions={increment(context,num){context.commit('UPDATE_COUNT',num)}}方法接受一个context对象,包含state,getters,commit,dispatch(asynchronousdistribution)在这个模块中,但它不是一个存储实例,你可以使用解构参数传入参数{commit,dispatch}constactions={increment({commit},num){context.commit('UPDATE_COUNT',num)}}mapActions:辅助函数,将store中的action映射到本地组件的method方法中)`到`this.$store.dispatch('increment')`...mapActiongs(['increment']),}一个完整的storeexportdefaultnewVuex.Store({state:{//storestate},getters:{//statecomputedproperty},mutations:{//在状态中改变状态的逻辑,同步操作},actions:{//提交突变,异步操作},modules:{//将store分成子模块,每个子模块都有自己的状态,mutations,actions,modules,在模块中写namespaced:true;是一个有命名空间的模块,使得模块更加封装和可复用,}});
