当前位置: 首页 > Web前端 > vue.js

简单版Vuex源码实现

时间:2023-03-31 22:16:02 vue.js

Vuex使用1.注册Vuex插件importVuexfrom'vuex'Vue.use(Vuex)2.创建Store实例exportdefaultnewVuex.Store({state:{count:0},mutations:{add(state,payload){state.count+=payload}},actions:{delayAdd(context,payload){setTimeout(()=>{context.commit("add",payload)},1000)}},getters:{doubleCount(state){returnstate.count*2}}})3.挂载到Vue根实例newVue({render:h=>h(App),store}).$mount('#app')4.使用this.$store.state.countthis.$store.getters.doubleCountthis.$store.commit('add',1)this.$store.dispatch('')在组件总结一下,Vuex需要做下面的事情来实现install方法。当Vueroot实例被实例化时,将store对象挂载到Vueroot实例。实现commit,同步修改state值实现dispatch,支持异步修改state值源码实现=选项。得到这个。得到ters={}conststoreComputed={}constself_store=thisObject.keys(this._wrappedGetters).forEach((key)=>{//遍历每个获取getters的方法constgettersFn=self_store._wrappedGetters[key]//转换tocomputed,即返回一个无参数的高阶函数storeComputed[key]=()=>{returngettersFn(self_store.state)}//定义getter为只读属性,可以枚举Object.defineProperty(self_store.getters,key,{get:()=>self_store._vm[key],enumerable:true})})//新建一个Vue实例_vm,在_vm中做数据响应处理this._vm=newVue({data:{$$state:options.state//添加$$表示不代理到Vue实例属性//Vue初始化在响应式处理数据时也会将数据代理到实例},computed:{...storeComputed}})console.log(this._vm)}getstate(){returnthis._vm._data.$$state}setstate(v){thrownewError(`usestore.replaceState()显式替换店铺state.`)}//这里你需要使用箭头函数来防止this改变//或者使用this.commit=this.commit.bind(this)Bindthiscommit=(type,payload)=>{//根据type从mutations中找到对应的方法constfn=this._mutations[type]if(!fn)returnfn.call(this,this.state,payload)}dispatch=(type,payload)=>{//根据type从actions中找到对应的methodconstfn=this._actions[type]if(!fn)returnfn.call(this,{commit:this.commit,state:this.state},payload)}}functioninstall(vue){/*1.判断插件是否已经安装2.保存vue构造函数3.通过混入,在创建根实例时挂载store实例*//1.判断插件是否已经安装if(Store.installed){return}Store.installed=true//2.保存vue构造函数Vue=vue//通过混入,在创建根实例时挂载storeExampleVue.mixin({beforeCreate(){if(this.$options.store){Vue.prototype.$store=this...安装到Vue原型。vue.prototype.$store=storeStore构造函数保存传入的配置选项,方便获取state、mutations、actions、getters等store.sta实现方式:通过new一个新的Vue实例_vm,将state存入_vm.data,state变成响应式数据重写state的set和get,防止直接修改state的值,只能通过commit和dispatch修改state的值,get从_vm.data中获取commit方法实现:commit需要绑定this为store实例,防止dispatch调用改变this点。通过入参类型,从mutations中取出函数执行,传入state参数dispatch方法:与commit方法类似,通过入参类型从action中取出函数执行,commitmethod和state保存在context中作为参数传递给getters实现:遍历getters的属性转换为_vm的computed,即返回一个无参数的高阶函数,get方法使用Object.defineProperty为每个键重新定义。不需要定义set来防止直接修改getter的值