实现一个简单的vuex
vuexhtml的用法兄弟年龄:{{$store.state.age}}兄弟年龄:{{$store.getters.getAge}}
storeimportVuefrom"vue";importVuexfrom"vuex";Vue.use(Vuex);exportdefaultnewVuex.Store({//statestate:{age:18},//等同于计算属性getters:{getAge(state){returnstate.age+10;}},//修改状态突变的方法:{changeAge(state,payload){state.age=state.age+payload;}},//仅解决同步而非异步操作的突变:{changeAge({commit},payload){setTimeout(()=>{commit("changeAge",payload);},1000);}}});mainimportstorefrom"./store";newVue({router,存储,渲染:h=>h(App)}).$mount("#app");简单实现vuex/indexvuex/index作为总导出,使用两种形式导出export{}===>import{Store}from'vuex'exportdefault===>importStorefrom'vuex'import{Store,install}from"./store";export{Store,install};exportdefault{Store,install,};vuex/storevuex/store.js这个文件为了方便写了install方法和Store类连同installinstall方法:usethestoreinnewVue({store})使用Vue的minxin方法递归遍历,这样所有的组件都可以通过$storeletVue获取;exportconstinstall=(_Vue)=>{Vue=_Vue;Vue.mixin({beforeCreate(){if(this.$options.store){this.$store=this.$options.store;}elseif(this.$options.parent&&this.$options.parent.$options.store){this.$store=this.$options.parent.$options.store;}},});};Storestate方法实现了install方法后,我们发现这样实现状态更方便。exportclassStore{constructor(options){this.state=options.state}}上面可以获取但是没有绑定state到双向数据,state改变时view不会改变,上面的install方法可以得到全局的Vue,这样我们就可以在Vue中使用observe对状态中的数据添加get和set方法exportclassStore{constructor(options){letstate=options.state;this._vm=newVue({data:{//$$是一个内部方法,没有挂载在实例上$$state:s泰特,},});}//取state的值时会触发该方法getstate(){returnthis._vm._data.$$state;}}公共方法forEach的实现exportconstforEach=(obj,fn)=>{Object.keys(obj).forEach((v)=>fn(v,obj[v]));};使用方法forEach({name:"Meng",val:"01"},(key,fn)=>{console.log(key,fn);});//传入一个对象,获取每个key对象和valgetters方法的实现getters在使用$store.getters时是一个对象。getAge,是getAge执行的结果this.getters={};让计算={};forEach(options.getters,(key,fn)=>{//每次其他数据发生变化刷新页面时,都会进行不必要的获取对于getters中的数据,computed有缓存的作用,如果数据没有变化,对应的方法不会被触发computed[key]=()=>{returnfn(this.state);};//getter的双向数据绑定Object.defineProperty(this.getters,key,{//computed是安装在实例上的属性get:()=>this._vm[key],});});this._vm=newVue({data:{$$state:state,},computed,});mutations实现mutations的方式是先将每个函数基于发布-订阅模型存储在事件池中,然后通过用户类Store的调度动作在事件池中执行相应的函数{constructor(options){this.mutations={};forEach(options.mutations,(key,fn)=>{this.mutations[key]=(payload)=>fn(this.state,payload);});}commit=(key,payload)=>{this.mutations[key](payload);};}actions的实现classStore{constructor(options){this.actions={};forEach(options.actions,(key,fn)=>{this.actions[key]=(payload)=>fn(this,payload);});dispatch=(key,payload)=>{this.actions[key](payload);};}